If you need slightly less control over formatting than the currently accepted answer, Date#toLocaleDateString can be used to create standard locale-specific renderings. The locale and options arguments let applications specify the language whose formatting conventions should be used, and allow some customization of the rendering.
Options key examples:
- day:
The representation of the day.
Possible values are "numeric", "2-digit". - weekday:
The representation of the weekday.
Possible values are "narrow", "short", "long". - year:
The representation of the year.
Possible values are "numeric", "2-digit". - month:
The representation of the month.
Possible values are "numeric", "2-digit", "narrow", "short", "long". - hour:
The representation of the hour.
Possible values are "numeric", "2-digit". - minute:
The representation of the minute.
Possible values are "numeric", "2-digit". - second:
The representation of the second.
Possible values are "numeric", 2-digit". - hour12:
The representation of time format.
Accepts boolean true or false
All these keys are optional. You can change the number of options values based on your requirements, and this will also reflect the presence of each date time term.
Note: If you would only like to configure the content options, but still use the current locale, passing null for the first parameter will cause an error. Use undefined instead.
For different languages:
- "en-US": For American English
- "en-GB": For British English
- "hi-IN": For Hindi
- "ja-JP": For Japanese
You can use more language options.
For example
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today = new Date();
console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016
You can also use the toLocaleString() method for the same purpose. The only difference is this function provides the time when you don't pass any options.
// Example
9/17/2016, 1:21:34 PM
References:
toLocaleString()toLocaleDateString()
Videos
If you need slightly less control over formatting than the currently accepted answer, Date#toLocaleDateString can be used to create standard locale-specific renderings. The locale and options arguments let applications specify the language whose formatting conventions should be used, and allow some customization of the rendering.
Options key examples:
- day:
The representation of the day.
Possible values are "numeric", "2-digit". - weekday:
The representation of the weekday.
Possible values are "narrow", "short", "long". - year:
The representation of the year.
Possible values are "numeric", "2-digit". - month:
The representation of the month.
Possible values are "numeric", "2-digit", "narrow", "short", "long". - hour:
The representation of the hour.
Possible values are "numeric", "2-digit". - minute:
The representation of the minute.
Possible values are "numeric", "2-digit". - second:
The representation of the second.
Possible values are "numeric", 2-digit". - hour12:
The representation of time format.
Accepts boolean true or false
All these keys are optional. You can change the number of options values based on your requirements, and this will also reflect the presence of each date time term.
Note: If you would only like to configure the content options, but still use the current locale, passing null for the first parameter will cause an error. Use undefined instead.
For different languages:
- "en-US": For American English
- "en-GB": For British English
- "hi-IN": For Hindi
- "ja-JP": For Japanese
You can use more language options.
For example
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today = new Date();
console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016
You can also use the toLocaleString() method for the same purpose. The only difference is this function provides the time when you don't pass any options.
// Example
9/17/2016, 1:21:34 PM
References:
toLocaleString()toLocaleDateString()
For custom-delimited date formats, you have to pull out the date (or time)
components from a DateTimeFormat object (which is part of the
ECMAScript Internationalization API), and then manually create a string
with the delimiters you want.
To do this, you can use DateTimeFormat#formatToParts. You could
destructure the array, but that is not ideal, as the array output depends on the
locale:
{ // example 1
let formatter = new Intl.DateTimeFormat('en');
let example = formatter.formatToParts();
console.log(example);
}
{ // example 2
let formatter = new Intl.DateTimeFormat('hi');
let example = formatter.formatToParts();
console.log(example);
}
Better would be to map a format array to resultant strings:
function join(date, options, separator) {
function format(option) {
let formatter = new Intl.DateTimeFormat('en', option);
return formatter.format(date);
}
return options.map(format).join(separator);
}
let options = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let joined = join(new Date, options, '-');
console.log(joined);
You can also pull out the parts of a DateTimeFormat one-by-one using
DateTimeFormat#format, but note that when using this method, as of March
2020, there is a bug in the ECMAScript implementation when it comes to
leading zeros on minutes and seconds (this bug is circumvented by the approach
above).
let date = new Date(2010, 7, 5);
let year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date);
let month = new Intl.DateTimeFormat('en', { month: 'short' }).format(date);
let day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date);
console.log(`
{month}-${year}`);
When working with dates and times, it is usually worth using a library (eg. luxon, date-fns, moment.js is not recommended for new projects) because of the many hidden complexities of the field.
Note that the ECMAScript Internationalization API, used in the solutions above is not supported in IE10 (0.03% global browser market share in Feb 2020).
I'm going insane. I had this feature working perfectly. Took 2 weeks vacation. I come back and it's broken.
I know y'all will say this is impossible, but I was getting that format by using `date.toLocaleDateString('en-CA')`. I know the spec says that format is "dd/MM/yyyy", which isn't what I want, but I was giving me the format in the title, I swear to God.
This is such a stupid little thing but I've already spent hours on SO. It's just endless threads about people confused about datetimes and the differences between timezones and offsets and no one's talking about this silly little thing.
I have my new date: Wed Feb 08 2023 00:00:00 GMT-0500 (Eastern Standard Time)
I just need a simple operation to flip the string around so it becomes 2023-03-08
That is it. Please help
p.s. the date is always set to midnight user local time so offset can be ignored. Whatever day they're experiencing is the day to be formatted. Thank you
Yes, you can use the native javascript Date() object and its methods.
For instance you can create a function like:
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var e = formatDate(d);
alert(e);
And display also the am / pm and the correct time.
Remember to use getFullYear() method and not getYear() because it has been deprecated.
DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/
Please do not reinvent the wheel. There are many open-source and COTS solutions that already exist to solve this problem.
Recommended
The following libraries are recommended for new projects.
Luxon (timezones, successor to Moment)
Luxon is the successor to the Moment.js library. It has native time zone and Intl support.
const { DateTime } = luxon;
const value = DateTime
.fromFormat("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss")
.toFormat('MM/dd/yyyy h:mm a');
console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.3.0/luxon.min.js"></script>
js-joda (fixes the Date object)
This is a port of the Joda-Time library in Java. Joda-Time became the java.time package in the Java JDK in version 1.8. It is the successor to the Date object and improves it significantly.
const { DateTimeFormat, DateTimeFormatter, LocalDateTime } = JSJoda;
const { Locale } = JSJodaLocale;
const value = LocalDateTime
.parse('2014-08-20 15:30:00',
DateTimeFormatter.ofPattern('yyyy-M-d HH:mm:ss'))
.format(DateTimeFormatter.ofPattern('MM/dd/yyyy h:mm a')
.withLocale(Locale.US));
console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js-joda.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@js-joda/[email protected]/dist/index.min.js"></script>
date-fns (fast, tree-shaking, server-side)
This is version 1.x, if you are using Node.js or another server-side JavaScript engine, you should use version 2.x.
const value = dateFns.format(
dateFns.parse("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss"),
'MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
Day.js (smallest footprint)
A minimalist date library with plugins.
const value = dayjs("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss")
.format('MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/dayjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/plugin/customParseFormat.min.js"></script>
date-and-time (small footprint)
A minimalist date library with plugins.
const value = date.format(
date.parse("2014-08-20 15:30:00", "YYYY-MM-DD HH:mm:ss"),
'MM/DD/YYYY h:mm A');
console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdn.jsdelivr.net/npm/[email protected]/date-and-time.min.js"></script>
Not recommended
The following libraries are not recommended for new projects, because they are either no longer supported or do not follow best practices.
Moment (timezones, legacy)
Here is the original version using Moment. Since Luxon is the successor to Moment, I have included this as an alternative.
const value = moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Date.js (small footprint, archived)
This library manipulates the Date prototype. This is not considered best practice.
const value = Date.parse('2014-08-20 15:30:00').toString('MM/dd/yyyy hh:mm tt');
console.log(value); // 08/20/2014 03:30 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
Without a library
Now, if you really don't want to use a library, a simple tokenizer can assist you in parsing and formatting.
const TOKENS = new Set(['Y', 'M', 'D', 'H', 'h', 'm', 's', 'a']);
const main = () => {
const value = format(parse('2014-08-20 15:30:00', 'YYYY-MM-DD HH:mm:ss'), 'MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
};
const parse = (input, pattern) =>
(tokens => new Date(
+tokens['Y'] , +tokens['M'] - 1 , +tokens['D'],
+tokens['H'] , +tokens['m'] , +tokens['s']
))(tokenize(input, pattern));
const format = (date, pattern) =>
pattern.replace(/\b(\w)(\1)*\b/g, (match) => {
switch (match[0]) {
case 'Y': return date.getFullYear();
case 'M': return `${date.getMonth() + 1}`.padStart(match.length, '0');
case 'D': return `${date.getDate()}`.padStart(match.length, '0');
case 'h': return `${date.getHours() % 12}`.padStart(match.length, '0');
case 'm': return `${date.getMinutes()}`.padStart(match.length, '0');
case 'a': return date.getHours() < 12 ? 'am' : 'pm';
}
return capture;
});
const tokenize = (input, pattern) =>
pattern.split('').reduce((acc, token, index) => TOKENS.has(token)
? { ...acc, [token]: (acc[token] ?? '') + input[index] }
: acc, {});
main();