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()
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).
Why doesn't JavaScript have a native Date() formatting method?
Convert date in JavaScript to yyyy-mm-dd format
How get a date formatted like 2023-02-07 in JS?
Javascript dates in a nutshell
YYYY-MM-DD uses the ISO 8601 shortened format. It assumes the time is based in GMT, and the date then adds the timezone offset for your computer.
new Date("2016-12-08")
Wed Dec 07 2016 16:00:00 GMT-0800 (PST)In order to get this back to the date that you wanted you would have to subtract the GMT offset. In this case, subtracting -8 from the resulting date will effectively add 8 hours to the time, giving Thurs Dec 8 at 00:00:00.
12/08/2016 uses the Javascript "short date" format, which is based on your computer's timezone, not GMT. When you type 12/08/2016 the time will be set to 00:00:00 within your own timezone. The result seems to be the correct date and time,
new Date("12/08/2016")
Thu Dec 08 2016 00:00:00 GMT-0800 (PST)http://www.w3schools.com/js/js_date_formats.asp
Edit: I should point out that ISO 8601 should be the standard for Javascript, and developers should shim the date display with a "subtractTimezoneOffset()" function which will fix the date for display purposes.
The real head scratcher is why "YYYY-MM-DDThh:mm:ss.sss-08:00" shows the correct date but the wrong timezone offset, but "YYYY-MM-DDThh:mm:ss.sssZ" and "YYYY-MM-DDThh:mm:ss.sss" add the timezone offset to produce the wrong date but the right timezone.
new Date("2016-12-08T00:00:00.000-08:00")
= Thu Dec 08 2016 00:00:00 GMT-0800 (PST)
new Date("2016-12-08T00:00:00.000")
= Wed Dec 07 2016 16:00:00 GMT-0800 (PST)
new Date("2016-12-08T00:00:00.000Z")
= Wed Dec 07 2016 16:00:00 GMT-0800 (PST) More on reddit.com Videos
Here's how you'd output today's time and date (10:30:14 03/21/2014, at the moment). Please correct any mistakes, as I'm not a PHP, JAVA, C# or PERL developer.
PHP
$today = date("h:i:s m/d/y");JAVA
String today = new SimpleDateFormat("hh:mm:ss MM/dd/yyyy").format(date);C#
DateTime date = new DateTime();
String today = date.ToString("H:mm:ss MM/dd/yyyy");PERL
my $today = strftime "%H:%M:%S %m/%d/%Y", localtime;
JavaScript
var d = new Date(),
month = d.getMonth() + 1,
day = (d.getDate() < 10) ? "0" + d.getDate() : d.getDate(),
year = d.getFullYear(),
hours = d.getHours(),
minutes = d.getMinutes(),
seconds = (d.getSeconds() < 10) ? "0" + d.getSeconds() : d.getSeconds();
if (hours > 12) {
hours -= 12;
} else if (hours === 0) {
hours = 12;
}
var today = hours + ":" + minutes + ":" + seconds + " " + month + "/" + day + "/" + year;WTF JavaScript? Y u so complicated???
Why can't we have something like .format() or .toString():
var today = new Date().format("h:i:s m/d/y")EDIT: Thanks for the answers everyone. It helped a lot.
I should've clarified originally that I was looking to find out WHY it's not native to the language, as opposed to HOW to do it via a 3rd party library (I'm aware of momentjs and it's great).
Anyway, the top 2 answers are great - exactly what I was looking for. Thank you.
I was unaware of Intl.DateTimeFormat (thanks u/SpsD3GoiFSmXBAl), which helps:
var date = new Date(),
today = new Intl.DateTimeFormat().format(date); // 3/24/2014 (also allows for customization options)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