javascript format date to legible format - javascript

I have this code which is getting me the date in a ledgible format but it currently outputs this format 20200819 but I want to convert it to 2020-08-19 is this possible?
This is my code
const dateConverter = (dateIn) => {
var yyyy = dateIn.getFullYear();
var mm = dateIn.getMonth() + 1; // getMonth() is zero-based
var dd = dateIn.getDate();
return String(10000 * yyyy + 100 * mm + dd); // Leading zeros for mm and dd
}
var today = new Date();
console.log(dateConverter(today));

You don't need the converter function for that. Just use toLocaleDateString with a locale that has this format, like Sweden.
To get more certainty about the format, I have added two extensions:
console.log(new Date().toLocaleDateString("en-se"));
// To be explicit about the format of the numerical parts
console.log(new Date().toLocaleDateString("en-se",
{ year: "numeric", month: "2-digit", day: "2-digit" })
);
// To be explicit about the delimiter also:
console.log(new Date().toLocaleDateString("en-se",
{ year: "numeric", month: "2-digit", day: "2-digit" })
.replace(/\D/g, "-")
);
Alternative:
If you don't want to rely on the native toLocaleDateString function, then replace the following line in your code:
return String(10000 * yyyy + 100 * mm + dd)
with:
return String(10000 * yyyy + 100 * mm + dd).replace(/(....)(..)(..)/,"$1-$2-$3");

You can use padStart to create your own string like below, but I would reccomend looking into the date-fns or moment.js libraries, as they can handle this very nicely.
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
console.log(dateConverter(today));

You could use template literals to get the format you want, im pretty sure their must be a simpler way but, this is as similar to your code as possible
const dateConverter = (dateIn) => {
var yyyy = dateIn.getFullYear();
var mm = dateIn.getMonth() + 1;
if (mm < 10) mm = `0${mm}`; // getMonth() is zero-based
var dd = dateIn.getDate();
if (dd < 10) dd = `0${dd}`;
return `${yyyy}-${mm}-${dd}`;
};
var today = new Date();
console.log(dateConverter(today));
Output as today : 2020-08-19

new Date().toISOString().slice(0, 10).split('-').reverse().join('/')
//use following date format methods and options.
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// formats below assume the local time zone of the locale;
// America/Los_Angeles for the US
// US English uses month-day-year order
console.log(date.toLocaleDateString('en-US'));
// → "12/19/2012"
// British English uses day-month-year order
console.log(date.toLocaleDateString('en-GB'));
// → "20/12/2012"
// Korean uses year-month-day order
console.log(date.toLocaleDateString('ko-KR'));
// → "2012. 12. 20."
// Event for Persian, It's hard to manually convert date to Solar Hijri
console.log(date.toLocaleDateString('fa-IR'));
// → "۱۳۹۱/۹/۳۰"
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleDateString('ar-EG'));
// → "٢٠‏/١٢‏/٢٠١٢"
// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(date.toLocaleDateString('ja-JP-u-ca-japanese'));
// → "24/12/20"
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(date.toLocaleDateString(['ban', 'id']));
// → "20/12/2012"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Related

Playwright Current Date +1 Day [duplicate]

I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?
function taskDate(dateMilli) {
var d = (new Date(dateMilli) + '').split(' ');
d[2] = d[2] + ',';
return [d[0], d[1], d[2], d[3]].join(' ');
}
var datemilli = Date.parse('Sun May 11,2014');
console.log(taskDate(datemilli));
The code above gives me the same date format, sun may 11,2014. How can I fix this?
Just leverage the built-in toISOString method that brings your date to the ISO 8601 format:
let yourDate = new Date()
yourDate.toISOString().split('T')[0]
Where yourDate is your date object.
Edit: #exbuddha wrote this to handle time zone in the comments:
const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]
You can do:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
console.log(formatDate('Sun May 11,2014'));
Usage example:
console.log(formatDate('Sun May 11,2014'));
Output:
2014-05-11
Demo on JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/
I use this way to get the date in format yyyy-mm-dd :)
var todayDate = new Date().toISOString().slice(0, 10);
console.log(todayDate);
2020 ANSWER
You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).
Examples
const testCases = [
new Date().toLocaleDateString(), // 8/19/2020
new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'}),
new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}), // 08/19/2020 (month and day with two digits)
new Date().toLocaleDateString('en-ZA'), // 2020/08/19 (year/month/day) notice the different locale
new Date().toLocaleDateString('en-CA'), // 2020-08-19 (year-month-day) notice the different locale
new Date().toLocaleString("en-US", {timeZone: "America/New_York"}), // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}), // 09 (just the hour)
]
for (const testData of testCases) {
console.log(testData)
}
Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format.
You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.
The simplest way to convert your date to the yyyy-mm-dd format, is to do this:
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
How it works:
new Date("Sun May 11,2014") converts the string "Sun May 11,2014" to a date object that represents the time Sun May 11 2014 00:00:00 in a timezone based on current locale (host system settings)
new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) converts your date to a date object that corresponds with the time Sun May 11 2014 00:00:00 in UTC (standard time) by subtracting the time zone offset
.toISOString() converts the date object to an ISO 8601 string 2014-05-11T00:00:00.000Z
.split("T") splits the string to array ["2014-05-11", "00:00:00.000Z"]
[0] takes the first element of that array
Demo
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
console.log(dateString);
Note :
The first part of the code (new Date(...)) may need to be tweaked a bit if your input format is different from that of the OP. As mikeypie
pointed out in the comments, if the date string is already in the expected output format and the local timezone is west of UTC, then new Date('2022-05-18') results in 2022-05-17. And a user's locale (eg. MM/DD/YYYY vs DD-MM-YYYY) may also impact how a date is parsed by new Date(...). So do some proper testing if you want to use this code for different input formats.
A combination of some of the answers:
var d = new Date(date);
date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2)
].join('-');
format = function date2str(x, y) {
var z = {
M: x.getMonth() + 1,
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
});
return y.replace(/(y+)/g, function(v) {
return x.getFullYear().toString().slice(-v.length)
});
}
Result:
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
If you don't have anything against using libraries, you could just use the Moments.js library like so:
var now = new Date();
var dateString = moment(now).format('YYYY-MM-DD');
var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
You can use toLocaleDateString('fr-CA') on Date object
console.log(new Date('Sun May 11,2014').toLocaleDateString('fr-CA'));
Also I found out that those locales give right result from this locales list List of All Locales and Their Short Codes?
'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'
var localesList = ["af-ZA",
"am-ET",
"ar-AE",
"ar-BH",
"ar-DZ",
"ar-EG",
"ar-IQ",
"ar-JO",
"ar-KW",
"ar-LB",
"ar-LY",
"ar-MA",
"arn-CL",
"ar-OM",
"ar-QA",
"ar-SA",
"ar-SY",
"ar-TN",
"ar-YE",
"as-IN",
"az-Cyrl-AZ",
"az-Latn-AZ",
"ba-RU",
"be-BY",
"bg-BG",
"bn-BD",
"bn-IN",
"bo-CN",
"br-FR",
"bs-Cyrl-BA",
"bs-Latn-BA",
"ca-ES",
"co-FR",
"cs-CZ",
"cy-GB",
"da-DK",
"de-AT",
"de-CH",
"de-DE",
"de-LI",
"de-LU",
"dsb-DE",
"dv-MV",
"el-GR",
"en-029",
"en-AU",
"en-BZ",
"en-CA",
"en-GB",
"en-IE",
"en-IN",
"en-JM",
"en-MY",
"en-NZ",
"en-PH",
"en-SG",
"en-TT",
"en-US",
"en-ZA",
"en-ZW",
"es-AR",
"es-BO",
"es-CL",
"es-CO",
"es-CR",
"es-DO",
"es-EC",
"es-ES",
"es-GT",
"es-HN",
"es-MX",
"es-NI",
"es-PA",
"es-PE",
"es-PR",
"es-PY",
"es-SV",
"es-US",
"es-UY",
"es-VE",
"et-EE",
"eu-ES",
"fa-IR",
"fi-FI",
"fil-PH",
"fo-FO",
"fr-BE",
"fr-CA",
"fr-CH",
"fr-FR",
"fr-LU",
"fr-MC",
"fy-NL",
"ga-IE",
"gd-GB",
"gl-ES",
"gsw-FR",
"gu-IN",
"ha-Latn-NG",
"he-IL",
"hi-IN",
"hr-BA",
"hr-HR",
"hsb-DE",
"hu-HU",
"hy-AM",
"id-ID",
"ig-NG",
"ii-CN",
"is-IS",
"it-CH",
"it-IT",
"iu-Cans-CA",
"iu-Latn-CA",
"ja-JP",
"ka-GE",
"kk-KZ",
"kl-GL",
"km-KH",
"kn-IN",
"kok-IN",
"ko-KR",
"ky-KG",
"lb-LU",
"lo-LA",
"lt-LT",
"lv-LV",
"mi-NZ",
"mk-MK",
"ml-IN",
"mn-MN",
"mn-Mong-CN",
"moh-CA",
"mr-IN",
"ms-BN",
"ms-MY",
"mt-MT",
"nb-NO",
"ne-NP",
"nl-BE",
"nl-NL",
"nn-NO",
"nso-ZA",
"oc-FR",
"or-IN",
"pa-IN",
"pl-PL",
"prs-AF",
"ps-AF",
"pt-BR",
"pt-PT",
"qut-GT",
"quz-BO",
"quz-EC",
"quz-PE",
"rm-CH",
"ro-RO",
"ru-RU",
"rw-RW",
"sah-RU",
"sa-IN",
"se-FI",
"se-NO",
"se-SE",
"si-LK",
"sk-SK",
"sl-SI",
"sma-NO",
"sma-SE",
"smj-NO",
"smj-SE",
"smn-FI",
"sms-FI",
"sq-AL",
"sr-Cyrl-BA",
"sr-Cyrl-CS",
"sr-Cyrl-ME",
"sr-Cyrl-RS",
"sr-Latn-BA",
"sr-Latn-CS",
"sr-Latn-ME",
"sr-Latn-RS",
"sv-FI",
"sv-SE",
"sw-KE",
"syr-SY",
"ta-IN",
"te-IN",
"tg-Cyrl-TJ",
"th-TH",
"tk-TM",
"tn-ZA",
"tr-TR",
"tt-RU",
"tzm-Latn-DZ",
"ug-CN",
"uk-UA",
"ur-PK",
"uz-Cyrl-UZ",
"uz-Latn-UZ",
"vi-VN",
"wo-SN",
"xh-ZA",
"yo-NG",
"zh-CN",
"zh-HK",
"zh-MO",
"zh-SG",
"zh-TW",
"zu-ZA"
];
localesList.forEach(lcl => {
if ("2014-05-11" === new Date('Sun May 11,2014').toLocaleDateString(lcl)) {
console.log(lcl, new Date('Sun May 11,2014').toLocaleDateString(lcl));
}
});
The 2021 solution using Intl.
The new Intl Object is now supported on all browsers.
You can choose the format by choosing a "locale" that uses the required format.
The Swedish locale uses the format "yyyy-mm-dd":
// Create a date
const date = new Date(2021, 10, 28);
// Create a formatter using the "sv-SE" locale
const dateFormatter = Intl.DateTimeFormat('sv-SE');
// Use the formatter to format the date
console.log(dateFormatter.format(date)); // "2021-11-28"
Downsides of using Intl:
You cannot "unformat" or "parse" strings using this method
You have to search for the required format (for instance on Wikipedia) and cannot use a format-string like "yyyy-mm-dd"
Simply use this:
var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
Simple and sweet ;)
Shortest
.toJSON().slice(0,10);
var d = new Date('Sun May 11,2014' +' UTC'); // Parse as UTC
let str = d.toJSON().slice(0,10); // Show as UTC
console.log(str);
toISOString() assumes your date is local time and converts it to UTC. You will get an incorrect date string.
The following method should return what you need.
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
In the most of cases (no time zone handling) this is enough:
date.toISOString().substring(0,10)
Example
var date = new Date();
console.log(date.toISOString()); // 2022-07-04T07:14:08.925Z
console.log(date.toISOString().substring(0,10)); // 2022-07-04
Retrieve year, month, and day, and then put them together. Straight, simple, and accurate.
function formatDate(date) {
var year = date.getFullYear().toString();
var month = (date.getMonth() + 101).toString().substring(1);
var day = (date.getDate() + 100).toString().substring(1);
return year + "-" + month + "-" + day;
}
//Usage example:
alert(formatDate(new Date()));
new Date('Tue Nov 01 2022 22:14:53 GMT-0300').toLocaleDateString('en-CA');
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );
or
new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]
Try this!
When ES2018 rolls around (works in chrome) you can simply regex it
(new Date())
.toISOString()
.replace(
/^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
'$<year>-$<month>-$<day>'
)
2020-07-14
Or if you'd like something pretty versatile with no libraries whatsoever
(new Date())
.toISOString()
.match(
/^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
)
.groups
Which results in extracting the following
{
H: "8"
HH: "08"
M: "45"
MM: "45"
S: "42"
SS: "42"
SSS: "42.855"
d: "14"
dd: "14"
m: "7"
mm: "07"
timezone: "Z"
yy: "20"
yyyy: "2020"
}
Which you can use like so with replace(..., '$<d>/$<m>/\'$<yy> # $<H>:$<MM>') as at the top instead of .match(...).groups to get
14/7/'20 # 8:45
const formatDate = d => [
d.getFullYear(),
(d.getMonth() + 1).toString().padStart(2, '0'),
d.getDate().toString().padStart(2, '0')
].join('-');
You can make use of padstart.
padStart(n, '0') ensures that a minimum of n characters are in a string and prepends it with '0's until that length is reached.
join('-') concatenates an array, adding '-' symbol between every elements.
getMonth() starts at 0 hence the +1.
To consider the timezone also, this one-liner should be good without any library:
new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
You can try this: https://www.npmjs.com/package/timesolver
npm i timesolver
Use it in your code:
const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");
You can get the date string by using this method:
getString
I suggest using something like formatDate-js instead of trying to replicate it every time. Just use a library that supports all the major strftime actions.
new Date().format("%Y-%m-%d")
Unfortunately, JavaScript's Date object has many pitfalls. Any solution based on Date's builtin toISOString has to mess with the timezone, as discussed in some other answers to this question. The clean solution to represent an ISO-8601 date (without time) is given by Temporal.PlainDate from the Temporal proposal. As of February 2021, you have to choose the workaround that works best for you.
use Date with vanilla string concatenation
Assuming that your internal representation is based on Date, you can perform manual string concatenation. The following code avoids some of Date's pitfalls (timezone, zero-based month, missing 2-digit formatting), but there might be other issues.
function vanillaToDateOnlyIso8601() {
// month May has zero-based index 4
const date = new Date(2014, 4, 11);
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, "0"); // month is zero-based
const dd = String(date.getDate()).padStart(2, "0");
if (yyyy < 1583) {
// TODO: decide how to support dates before 1583
throw new Error(`dates before year 1583 are not supported`);
}
const formatted = `${yyyy}-${mm}-${dd}`;
console.log("vanilla", formatted);
}
use Date with helper library (e.g. formatISO from date-fns)
This is a popular approach, but you are still forced to handle a calendar date as a Date, which represents
a single moment in time in a platform-independent format
The following code should get the job done, though:
import { formatISO } from "date-fns";
function dateFnsToDateOnlyIso8601() {
// month May has zero-based index 4
const date = new Date(2014, 4, 11);
const formatted = formatISO(date, { representation: "date" });
console.log("date-fns", formatted);
}
find a library that properly represents dates and times
I wish there was a clean and battle-tested library that brings its own well-designed date–time representations. A promising candidate for the task in this question was LocalDate from #js-joda/core, but the library is less active than, say, date-fns. When playing around with some example code, I also had some issues after adding the optional #js-joda/timezone.
However, the core functionality works and looks very clean to me:
import { LocalDate, Month } from "#js-joda/core";
function jodaDateOnlyIso8601() {
const someDay = LocalDate.of(2014, Month.MAY, 11);
const formatted = someDay.toString();
console.log("joda", formatted);
}
experiment with the Temporal-proposal polyfill
This is not recommended for production, but you can import the future if you wish:
import { Temporal } from "proposal-temporal";
function temporalDateOnlyIso8601() {
// yep, month is one-based here (as of Feb 2021)
const plainDate = new Temporal.PlainDate(2014, 5, 11);
const formatted = plainDate.toString();
console.log("proposal-temporal", formatted);
}
Here is one way to do it:
var date = Date.parse('Sun May 11,2014');
function format(date) {
date = new Date(date);
var day = ('0' + date.getDate()).slice(-2);
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var year = date.getFullYear();
return year + '-' + month + '-' + day;
}
console.log(format(date));
Date.js is great for this.
require("datejs")
(new Date()).toString("yyyy-MM-dd")
Simply Retrieve year, month, and day, and then put them together.
function dateFormat(date) {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${year}-${month}-${day}`;
}
console.log(dateFormat(new Date()));
None of these answers quite satisfied me. I wanted a cross-platform solution that gave me the day in the local timezone without using any external libraries.
This is what I came up with:
function localDay(time) {
var minutesOffset = time.getTimezoneOffset()
var millisecondsOffset = minutesOffset*60*1000
var local = new Date(time - millisecondsOffset)
return local.toISOString().substr(0, 10)
}
That should return the day of the date, in YYYY-MM-DD format, in the timezone the date references.
So for example, localDay(new Date("2017-08-24T03:29:22.099Z")) will return "2017-08-23" even though it's already the 24th at UTC.
You'll need to polyfill Date.prototype.toISOString for it to work in Internet Explorer 8, but it should be supported everywhere else.
A few of the previous answer were OK, but they weren't very flexible. I wanted something that could really handle more edge cases, so I took #orangleliu 's answer and expanded on it. https://jsfiddle.net/8904cmLd/1/
function DateToString(inDate, formatString) {
// Written by m1m1k 2018-04-05
// Validate that we're working with a date
if(!isValidDate(inDate))
{
inDate = new Date(inDate);
}
// See the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014', 'USA');
//formatString = CountryCodeToDateFormat(formatString);
var dateObject = {
M: inDate.getMonth() + 1,
d: inDate.getDate(),
D: inDate.getDate(),
h: inDate.getHours(),
m: inDate.getMinutes(),
s: inDate.getSeconds(),
y: inDate.getFullYear(),
Y: inDate.getFullYear()
};
// Build Regex Dynamically based on the list above.
// It should end up with something like this: "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
var dateMatchRegex = joinObj(dateObject, "+|") + "+";
var regEx = new RegExp(dateMatchRegex,"g");
formatString = formatString.replace(regEx, function(formatToken) {
var datePartValue = dateObject[formatToken.slice(-1)];
var tokenLength = formatToken.length;
// A conflict exists between specifying 'd' for no zero pad -> expand
// to '10' and specifying yy for just two year digits '01' instead
// of '2001'. One expands, the other contracts.
//
// So Constrict Years but Expand All Else
if (formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
{
// Expand single digit format token 'd' to
// multi digit value '10' when needed
var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
}
var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
return (zeroPad + datePartValue).slice(-tokenLength);
});
return formatString;
}
Example usage:
DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');
If you use momentjs, now they include a constant for that format YYYY-MM-DD:
date.format(moment.HTML5_FMT.DATE)
Yet another combination of the answers. Nicely readable, but a little lengthy.
function getCurrentDayTimestamp() {
const d = new Date();
return new Date(
Date.UTC(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
d.getSeconds()
)
// `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
// and we want the first part ("2017-08-22")
).toISOString().slice(0, 10);
}
Reformatting a date string is fairly straightforward, e.g.
var s = 'Sun May 11,2014';
function reformatDate(s) {
function z(n){return ('0' + n).slice(-2)}
var months = [,'jan','feb','mar','apr','may','jun',
'jul','aug','sep','oct','nov','dec'];
var b = s.split(/\W+/);
return b[3] + '-' +
z(months.indexOf(b[1].substr(0,3).toLowerCase())) + '-' +
z(b[2]);
}
console.log(reformatDate(s));

Jquery Date Format Conversion [duplicate]

I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?
function taskDate(dateMilli) {
var d = (new Date(dateMilli) + '').split(' ');
d[2] = d[2] + ',';
return [d[0], d[1], d[2], d[3]].join(' ');
}
var datemilli = Date.parse('Sun May 11,2014');
console.log(taskDate(datemilli));
The code above gives me the same date format, sun may 11,2014. How can I fix this?
Just leverage the built-in toISOString method that brings your date to the ISO 8601 format:
let yourDate = new Date()
yourDate.toISOString().split('T')[0]
Where yourDate is your date object.
Edit: #exbuddha wrote this to handle time zone in the comments:
const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]
You can do:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
console.log(formatDate('Sun May 11,2014'));
Usage example:
console.log(formatDate('Sun May 11,2014'));
Output:
2014-05-11
Demo on JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/
I use this way to get the date in format yyyy-mm-dd :)
var todayDate = new Date().toISOString().slice(0, 10);
console.log(todayDate);
2020 ANSWER
You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).
Examples
const testCases = [
new Date().toLocaleDateString(), // 8/19/2020
new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'}),
new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}), // 08/19/2020 (month and day with two digits)
new Date().toLocaleDateString('en-ZA'), // 2020/08/19 (year/month/day) notice the different locale
new Date().toLocaleDateString('en-CA'), // 2020-08-19 (year-month-day) notice the different locale
new Date().toLocaleString("en-US", {timeZone: "America/New_York"}), // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}), // 09 (just the hour)
]
for (const testData of testCases) {
console.log(testData)
}
Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format.
You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.
The simplest way to convert your date to the yyyy-mm-dd format, is to do this:
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
How it works:
new Date("Sun May 11,2014") converts the string "Sun May 11,2014" to a date object that represents the time Sun May 11 2014 00:00:00 in a timezone based on current locale (host system settings)
new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) converts your date to a date object that corresponds with the time Sun May 11 2014 00:00:00 in UTC (standard time) by subtracting the time zone offset
.toISOString() converts the date object to an ISO 8601 string 2014-05-11T00:00:00.000Z
.split("T") splits the string to array ["2014-05-11", "00:00:00.000Z"]
[0] takes the first element of that array
Demo
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
console.log(dateString);
Note :
The first part of the code (new Date(...)) may need to be tweaked a bit if your input format is different from that of the OP. As mikeypie
pointed out in the comments, if the date string is already in the expected output format and the local timezone is west of UTC, then new Date('2022-05-18') results in 2022-05-17. And a user's locale (eg. MM/DD/YYYY vs DD-MM-YYYY) may also impact how a date is parsed by new Date(...). So do some proper testing if you want to use this code for different input formats.
A combination of some of the answers:
var d = new Date(date);
date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2)
].join('-');
format = function date2str(x, y) {
var z = {
M: x.getMonth() + 1,
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
});
return y.replace(/(y+)/g, function(v) {
return x.getFullYear().toString().slice(-v.length)
});
}
Result:
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
If you don't have anything against using libraries, you could just use the Moments.js library like so:
var now = new Date();
var dateString = moment(now).format('YYYY-MM-DD');
var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
You can use toLocaleDateString('fr-CA') on Date object
console.log(new Date('Sun May 11,2014').toLocaleDateString('fr-CA'));
Also I found out that those locales give right result from this locales list List of All Locales and Their Short Codes?
'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'
var localesList = ["af-ZA",
"am-ET",
"ar-AE",
"ar-BH",
"ar-DZ",
"ar-EG",
"ar-IQ",
"ar-JO",
"ar-KW",
"ar-LB",
"ar-LY",
"ar-MA",
"arn-CL",
"ar-OM",
"ar-QA",
"ar-SA",
"ar-SY",
"ar-TN",
"ar-YE",
"as-IN",
"az-Cyrl-AZ",
"az-Latn-AZ",
"ba-RU",
"be-BY",
"bg-BG",
"bn-BD",
"bn-IN",
"bo-CN",
"br-FR",
"bs-Cyrl-BA",
"bs-Latn-BA",
"ca-ES",
"co-FR",
"cs-CZ",
"cy-GB",
"da-DK",
"de-AT",
"de-CH",
"de-DE",
"de-LI",
"de-LU",
"dsb-DE",
"dv-MV",
"el-GR",
"en-029",
"en-AU",
"en-BZ",
"en-CA",
"en-GB",
"en-IE",
"en-IN",
"en-JM",
"en-MY",
"en-NZ",
"en-PH",
"en-SG",
"en-TT",
"en-US",
"en-ZA",
"en-ZW",
"es-AR",
"es-BO",
"es-CL",
"es-CO",
"es-CR",
"es-DO",
"es-EC",
"es-ES",
"es-GT",
"es-HN",
"es-MX",
"es-NI",
"es-PA",
"es-PE",
"es-PR",
"es-PY",
"es-SV",
"es-US",
"es-UY",
"es-VE",
"et-EE",
"eu-ES",
"fa-IR",
"fi-FI",
"fil-PH",
"fo-FO",
"fr-BE",
"fr-CA",
"fr-CH",
"fr-FR",
"fr-LU",
"fr-MC",
"fy-NL",
"ga-IE",
"gd-GB",
"gl-ES",
"gsw-FR",
"gu-IN",
"ha-Latn-NG",
"he-IL",
"hi-IN",
"hr-BA",
"hr-HR",
"hsb-DE",
"hu-HU",
"hy-AM",
"id-ID",
"ig-NG",
"ii-CN",
"is-IS",
"it-CH",
"it-IT",
"iu-Cans-CA",
"iu-Latn-CA",
"ja-JP",
"ka-GE",
"kk-KZ",
"kl-GL",
"km-KH",
"kn-IN",
"kok-IN",
"ko-KR",
"ky-KG",
"lb-LU",
"lo-LA",
"lt-LT",
"lv-LV",
"mi-NZ",
"mk-MK",
"ml-IN",
"mn-MN",
"mn-Mong-CN",
"moh-CA",
"mr-IN",
"ms-BN",
"ms-MY",
"mt-MT",
"nb-NO",
"ne-NP",
"nl-BE",
"nl-NL",
"nn-NO",
"nso-ZA",
"oc-FR",
"or-IN",
"pa-IN",
"pl-PL",
"prs-AF",
"ps-AF",
"pt-BR",
"pt-PT",
"qut-GT",
"quz-BO",
"quz-EC",
"quz-PE",
"rm-CH",
"ro-RO",
"ru-RU",
"rw-RW",
"sah-RU",
"sa-IN",
"se-FI",
"se-NO",
"se-SE",
"si-LK",
"sk-SK",
"sl-SI",
"sma-NO",
"sma-SE",
"smj-NO",
"smj-SE",
"smn-FI",
"sms-FI",
"sq-AL",
"sr-Cyrl-BA",
"sr-Cyrl-CS",
"sr-Cyrl-ME",
"sr-Cyrl-RS",
"sr-Latn-BA",
"sr-Latn-CS",
"sr-Latn-ME",
"sr-Latn-RS",
"sv-FI",
"sv-SE",
"sw-KE",
"syr-SY",
"ta-IN",
"te-IN",
"tg-Cyrl-TJ",
"th-TH",
"tk-TM",
"tn-ZA",
"tr-TR",
"tt-RU",
"tzm-Latn-DZ",
"ug-CN",
"uk-UA",
"ur-PK",
"uz-Cyrl-UZ",
"uz-Latn-UZ",
"vi-VN",
"wo-SN",
"xh-ZA",
"yo-NG",
"zh-CN",
"zh-HK",
"zh-MO",
"zh-SG",
"zh-TW",
"zu-ZA"
];
localesList.forEach(lcl => {
if ("2014-05-11" === new Date('Sun May 11,2014').toLocaleDateString(lcl)) {
console.log(lcl, new Date('Sun May 11,2014').toLocaleDateString(lcl));
}
});
The 2021 solution using Intl.
The new Intl Object is now supported on all browsers.
You can choose the format by choosing a "locale" that uses the required format.
The Swedish locale uses the format "yyyy-mm-dd":
// Create a date
const date = new Date(2021, 10, 28);
// Create a formatter using the "sv-SE" locale
const dateFormatter = Intl.DateTimeFormat('sv-SE');
// Use the formatter to format the date
console.log(dateFormatter.format(date)); // "2021-11-28"
Downsides of using Intl:
You cannot "unformat" or "parse" strings using this method
You have to search for the required format (for instance on Wikipedia) and cannot use a format-string like "yyyy-mm-dd"
Simply use this:
var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
Simple and sweet ;)
Shortest
.toJSON().slice(0,10);
var d = new Date('Sun May 11,2014' +' UTC'); // Parse as UTC
let str = d.toJSON().slice(0,10); // Show as UTC
console.log(str);
toISOString() assumes your date is local time and converts it to UTC. You will get an incorrect date string.
The following method should return what you need.
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
In the most of cases (no time zone handling) this is enough:
date.toISOString().substring(0,10)
Example
var date = new Date();
console.log(date.toISOString()); // 2022-07-04T07:14:08.925Z
console.log(date.toISOString().substring(0,10)); // 2022-07-04
Retrieve year, month, and day, and then put them together. Straight, simple, and accurate.
function formatDate(date) {
var year = date.getFullYear().toString();
var month = (date.getMonth() + 101).toString().substring(1);
var day = (date.getDate() + 100).toString().substring(1);
return year + "-" + month + "-" + day;
}
//Usage example:
alert(formatDate(new Date()));
new Date('Tue Nov 01 2022 22:14:53 GMT-0300').toLocaleDateString('en-CA');
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );
or
new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]
Try this!
When ES2018 rolls around (works in chrome) you can simply regex it
(new Date())
.toISOString()
.replace(
/^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
'$<year>-$<month>-$<day>'
)
2020-07-14
Or if you'd like something pretty versatile with no libraries whatsoever
(new Date())
.toISOString()
.match(
/^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
)
.groups
Which results in extracting the following
{
H: "8"
HH: "08"
M: "45"
MM: "45"
S: "42"
SS: "42"
SSS: "42.855"
d: "14"
dd: "14"
m: "7"
mm: "07"
timezone: "Z"
yy: "20"
yyyy: "2020"
}
Which you can use like so with replace(..., '$<d>/$<m>/\'$<yy> # $<H>:$<MM>') as at the top instead of .match(...).groups to get
14/7/'20 # 8:45
const formatDate = d => [
d.getFullYear(),
(d.getMonth() + 1).toString().padStart(2, '0'),
d.getDate().toString().padStart(2, '0')
].join('-');
You can make use of padstart.
padStart(n, '0') ensures that a minimum of n characters are in a string and prepends it with '0's until that length is reached.
join('-') concatenates an array, adding '-' symbol between every elements.
getMonth() starts at 0 hence the +1.
To consider the timezone also, this one-liner should be good without any library:
new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
You can try this: https://www.npmjs.com/package/timesolver
npm i timesolver
Use it in your code:
const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");
You can get the date string by using this method:
getString
I suggest using something like formatDate-js instead of trying to replicate it every time. Just use a library that supports all the major strftime actions.
new Date().format("%Y-%m-%d")
Unfortunately, JavaScript's Date object has many pitfalls. Any solution based on Date's builtin toISOString has to mess with the timezone, as discussed in some other answers to this question. The clean solution to represent an ISO-8601 date (without time) is given by Temporal.PlainDate from the Temporal proposal. As of February 2021, you have to choose the workaround that works best for you.
use Date with vanilla string concatenation
Assuming that your internal representation is based on Date, you can perform manual string concatenation. The following code avoids some of Date's pitfalls (timezone, zero-based month, missing 2-digit formatting), but there might be other issues.
function vanillaToDateOnlyIso8601() {
// month May has zero-based index 4
const date = new Date(2014, 4, 11);
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, "0"); // month is zero-based
const dd = String(date.getDate()).padStart(2, "0");
if (yyyy < 1583) {
// TODO: decide how to support dates before 1583
throw new Error(`dates before year 1583 are not supported`);
}
const formatted = `${yyyy}-${mm}-${dd}`;
console.log("vanilla", formatted);
}
use Date with helper library (e.g. formatISO from date-fns)
This is a popular approach, but you are still forced to handle a calendar date as a Date, which represents
a single moment in time in a platform-independent format
The following code should get the job done, though:
import { formatISO } from "date-fns";
function dateFnsToDateOnlyIso8601() {
// month May has zero-based index 4
const date = new Date(2014, 4, 11);
const formatted = formatISO(date, { representation: "date" });
console.log("date-fns", formatted);
}
find a library that properly represents dates and times
I wish there was a clean and battle-tested library that brings its own well-designed date–time representations. A promising candidate for the task in this question was LocalDate from #js-joda/core, but the library is less active than, say, date-fns. When playing around with some example code, I also had some issues after adding the optional #js-joda/timezone.
However, the core functionality works and looks very clean to me:
import { LocalDate, Month } from "#js-joda/core";
function jodaDateOnlyIso8601() {
const someDay = LocalDate.of(2014, Month.MAY, 11);
const formatted = someDay.toString();
console.log("joda", formatted);
}
experiment with the Temporal-proposal polyfill
This is not recommended for production, but you can import the future if you wish:
import { Temporal } from "proposal-temporal";
function temporalDateOnlyIso8601() {
// yep, month is one-based here (as of Feb 2021)
const plainDate = new Temporal.PlainDate(2014, 5, 11);
const formatted = plainDate.toString();
console.log("proposal-temporal", formatted);
}
Here is one way to do it:
var date = Date.parse('Sun May 11,2014');
function format(date) {
date = new Date(date);
var day = ('0' + date.getDate()).slice(-2);
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var year = date.getFullYear();
return year + '-' + month + '-' + day;
}
console.log(format(date));
Date.js is great for this.
require("datejs")
(new Date()).toString("yyyy-MM-dd")
Simply Retrieve year, month, and day, and then put them together.
function dateFormat(date) {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${year}-${month}-${day}`;
}
console.log(dateFormat(new Date()));
None of these answers quite satisfied me. I wanted a cross-platform solution that gave me the day in the local timezone without using any external libraries.
This is what I came up with:
function localDay(time) {
var minutesOffset = time.getTimezoneOffset()
var millisecondsOffset = minutesOffset*60*1000
var local = new Date(time - millisecondsOffset)
return local.toISOString().substr(0, 10)
}
That should return the day of the date, in YYYY-MM-DD format, in the timezone the date references.
So for example, localDay(new Date("2017-08-24T03:29:22.099Z")) will return "2017-08-23" even though it's already the 24th at UTC.
You'll need to polyfill Date.prototype.toISOString for it to work in Internet Explorer 8, but it should be supported everywhere else.
A few of the previous answer were OK, but they weren't very flexible. I wanted something that could really handle more edge cases, so I took #orangleliu 's answer and expanded on it. https://jsfiddle.net/8904cmLd/1/
function DateToString(inDate, formatString) {
// Written by m1m1k 2018-04-05
// Validate that we're working with a date
if(!isValidDate(inDate))
{
inDate = new Date(inDate);
}
// See the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014', 'USA');
//formatString = CountryCodeToDateFormat(formatString);
var dateObject = {
M: inDate.getMonth() + 1,
d: inDate.getDate(),
D: inDate.getDate(),
h: inDate.getHours(),
m: inDate.getMinutes(),
s: inDate.getSeconds(),
y: inDate.getFullYear(),
Y: inDate.getFullYear()
};
// Build Regex Dynamically based on the list above.
// It should end up with something like this: "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
var dateMatchRegex = joinObj(dateObject, "+|") + "+";
var regEx = new RegExp(dateMatchRegex,"g");
formatString = formatString.replace(regEx, function(formatToken) {
var datePartValue = dateObject[formatToken.slice(-1)];
var tokenLength = formatToken.length;
// A conflict exists between specifying 'd' for no zero pad -> expand
// to '10' and specifying yy for just two year digits '01' instead
// of '2001'. One expands, the other contracts.
//
// So Constrict Years but Expand All Else
if (formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
{
// Expand single digit format token 'd' to
// multi digit value '10' when needed
var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
}
var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
return (zeroPad + datePartValue).slice(-tokenLength);
});
return formatString;
}
Example usage:
DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');
If you use momentjs, now they include a constant for that format YYYY-MM-DD:
date.format(moment.HTML5_FMT.DATE)
You can use this function for better format and easy of use:
function convert(date) {
const d = Date.parse(date)
const date_obj = new Date(d)
return `${date_obj.getFullYear()}-${date_obj.toLocaleString("default", { month: "2-digit" })}-${date_obj.toLocaleString("default", { day: "2-digit"})}`
}
This function will format the month as 2-digit output as well as the days
Yet another combination of the answers. Nicely readable, but a little lengthy.
function getCurrentDayTimestamp() {
const d = new Date();
return new Date(
Date.UTC(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
d.getSeconds()
)
// `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
// and we want the first part ("2017-08-22")
).toISOString().slice(0, 10);
}

How to convert an ISO date to the date format yyyy-mm-dd?

How can I get a date having the format yyyy-mm-dd from an ISO 8601 date?
My 8601 date is
2013-03-10T02:00:00Z
How can I get the following?
2013-03-10
Just crop the string:
var date = new Date("2013-03-10T02:00:00Z");
date.toISOString().substring(0, 10);
Or if you need only date out of string.
var strDate = "2013-03-10T02:00:00Z";
strDate.substring(0, 10);
Try this
date = new Date('2013-03-10T02:00:00Z');
date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();//prints expected format.
Update:-
As pointed out in comments, I am updating the answer to print leading zeros for date and month if needed.
date = new Date('2013-08-03T02:00:00Z');
year = date.getFullYear();
month = date.getMonth()+1;
dt = date.getDate();
if (dt < 10) {
dt = '0' + dt;
}
if (month < 10) {
month = '0' + month;
}
console.log(year+'-' + month + '-'+dt);
You could checkout Moment.js, Luxon, date-fns or Day.js for nice date manipulation.
Or just extract the first part of your ISO string, it already contains what you want.
Here is an example by splitting on the T:
"2013-03-10T02:00:00Z".split("T")[0] // "2013-03-10"
And another example by extracting the 10 first characters:
"2013-03-10T02:00:00Z".substr(0, 10) // "2013-03-10"
This is what I do to get date only:
let isoDate = "2013-03-10T02:00:00Z";
alert(isoDate.split("T")[0]);
let isoDate = "2013-03-10T02:00:00Z";
var d = new Date(isoDate);
d.toLocaleDateString('en-GB'); // dd/mm/yyyy
d.toLocaleDateString('en-US'); // mm/dd/yyyy
Moment.js will handle date formatting for you. Here is how to include it via a JavaScript tag, and then an example of how to use Moment.js to format a date.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
moment("2013-03-10T02:00:00Z").format("YYYY-MM-DD") // "2013-03-10"
Moment.js is pretty big library to use for a single use case. I recommend using date-fns instead. It offers basically the most functionality of Moment.js with a much smaller bundle size and many formatting options.
import format from 'date-fns/format'
format('2013-03-10T02:00:00Z', 'YYYY-MM-DD'); // 2013-03-10, YYYY-MM-dd for 2.x
One thing to note is that, since it's the ISO 8601 time format, the browser generally converts from UTC time to local timezone. Though this is simple use case where you can probably do '2013-03-10T02:00:00Z'.substring(0, 10);.
For more complex conversions date-fns is the way to go.
UPDATE: This no longer works with Firefox and Chromium v110+ (Feb 2023) because the 'en-CA' locale now returns the US date format.
Using toLocaleDateString with the Canadian locale returns a date in ISO format.
function getISODate(date) {
return date.toLocaleDateString('en-ca');
}
getISODate(new Date()); // '2022-03-24'
To all who are using split, slice and other string-based attempts to obtain the date, you might set yourself up for timezone related fails!
An ISO-String has Zulu-Timezone and a date according to this timezone, which means, it might use a date a day prior or later to the actual timezone, which you have to take into account in your transformation chain.
See this example:
const timeZoneRelatedDate = new Date(2020, 0, 14, 0, 0);
console.log(timeZoneRelatedDate.toLocaleDateString(
'ja-JP',
{
year: 'numeric',
month: '2-digit',
day: '2-digit'
}
).replace(/\//gi,'-'));
// RESULT: "2020-01-14"
console.log(timeZoneRelatedDate.toISOString());
// RESULT: "2020-01-13T23:00:00.000Z" (for me in UTC+1)
console.log(timeZoneRelatedDate.toISOString().slice(0,10));
// RESULT: "2020-01-13"
Use:
new Date().toISOString().substring(0, 10);
This will output the date in YYYY-MM-DD format:
let date = new Date();
date = date.toISOString().slice(0,10);
The best way to format is by using toLocaleDateString with options
const options = {year: 'numeric', month: 'numeric', day: 'numeric' };
const date = new Date('2013-03-10T02:00:00Z').toLocaleDateString('en-EN', options)
Check Date section for date options here https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Pass your date in the date object:
var d = new Date('2013-03-10T02:00:00Z');
d.toLocaleDateString().replace(/\//g, '-');
If you have a date object:
let date = new Date()
let result = date.toISOString().split`T`[0]
console.log(result)
or
let date = new Date()
let result = date.toISOString().slice(0, 10)
console.log(result)
To extend on rk rk's solution: In case you want the format to include the time, you can add the toTimeString() to your string, and then strip the GMT part, as follows:
var d = new Date('2013-03-10T02:00:00Z');
var fd = d.toLocaleDateString() + ' ' + d.toTimeString().substring(0, d.toTimeString().indexOf("GMT"));
A better version of answer by #Hozefa.
If you have date-fns installed, you could use formatISO function
const date = new Date(2019, 0, 2)
import { formatISO } from 'date-fns'
formatISO(date, { representation: 'date' }) // '2019-01-02' string
If you have the timezone you can do:
const myDate = "2022-10-09T18:30:00.000Z"
const requestTimezone = "Asia/Calcutta";
const newDate = new Date(myDate).toLocaleString("en-CA", {
dateStyle: "short",
timeZone: requestTimezone,
});
console.log(newDate)
>> 2022-10-10
Another outputs:
const myDate = "2022-10-02T21:00:00.000Z"
const requestTimezone = "Asia/Jerusalem";
>> 2022-10-03
const myDate = "2022-09-28T04:00:00.000Z"
const requestTimezone = "America/New_York";
>> 2022-09-28
I used this:
HTMLDatetoIsoDate(htmlDate){
let year = Number(htmlDate.toString().substring(0, 4))
let month = Number(htmlDate.toString().substring(5, 7))
let day = Number(htmlDate.toString().substring(8, 10))
return new Date(year, month - 1, day)
}
isoDateToHtmlDate(isoDate){
let date = new Date(isoDate);
let dtString = ''
let monthString = ''
if (date.getDate() < 10) {
dtString = '0' + date.getDate();
} else {
dtString = String(date.getDate())
}
if (date.getMonth()+1 < 10) {
monthString = '0' + Number(date.getMonth()+1);
} else {
monthString = String(date.getMonth()+1);
}
return date.getFullYear()+'-' + monthString + '-'+dtString
}
Source: http://gooplus.fr/en/2017/07/13/angular2-typescript-isodate-to-html-date/
var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
alert(d.toLocaleDateString());
let dt = new Date('2013-03-10T02:00:00Z');
let dd = dt.getDate();
let mm = dt.getMonth() + 1;
let yyyy = dt.getFullYear();
if (dd<10) {
dd = '0' + dd;
}
if (mm<10) {
mm = '0' + mm;
}
return yyyy + '-' + mm + '-' + dd;
Many of these answers give potentially misleading output if one is looking for the day in the current timezone.
This function will output the day corresponding with the date's timezone offset:
const adjustDateToLocalTimeZoneDayString = (date?: Date) => {
if (!date) {
return undefined;
}
const dateCopy = new Date(date);
dateCopy.setTime(dateCopy.getTime() - dateCopy.getTimezoneOffset()*60*1000);
return dateCopy.toISOString().split('T')[0];
};
Tests:
it('return correct day even if timezone is included', () => {
// assuming the test is running in EDT timezone
// 11:34pm eastern time would be the next day in GMT
let result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0400'));
// Note: This is probably what a person wants, the date in the current timezone
expect(result).toEqual('2022-04-06');
// 11:34pm zulu time should be the same
result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0000'));
expect(result).toEqual('2022-04-06');
result = adjustDateToLocalTimeZoneDayString(undefined);
expect(result).toBeUndefined();
});
Misleading approach:
To demonstrate the issue with the other answers' direct ISOString().split() approach, note how the output below differs from what one might expect:
it('demonstrates how the simple ISOString().split() may be misleading', () => {
// Note this is the 7th
expect(new Date('Wed Apr 06 2022 23:34:17 GMT-0400').toISOString().split('T')[0]).toEqual('2022-04-07');
});
Simpler way to get Year Or Month
let isoDateTime = "2013-03-10T02:00:00Z";
console.log(isoDateTime.split("T")[0]); //2013-03-10
Using Split Method
console.log(isoDateTime.split("-")[0]); //2013
console.log(isoDateTime.split("-")[1]); //03
WARNING: Most of these answers are wrong.
That is because toISOString() always returns the UTC date, not local date. So, for example, if your UTC time is 0500 and your timezone is GMT-0800, the day returned by toISOString() will be the UTC day, which will be one day ahead of the local timezone day.
You need to first convert the date to the local date.
const date = new Date();
date.setTime(date.getTime() - date.getTimezoneOffset()*60*1000)
Now date.toISOString() will always return the proper date according to the local timezone.
But wait, there's more. If we are also using toTimeString() that will now be wrong because time is now local and toTimeString() assumes it is UTC and converts it. So we need to first extract toTimeString() as a variable before doing the conversion.
The Date() class in javascript is inconsistent because of this and should really be updated to avoid this confusion. The toISOString() and toTimeString() methods should both do the same default things with respect to timezone.
Use the below code. It is useful for you.
let currentDate = new Date()
currentDate.toISOString()

How can I get time from ISO 8601 time format in JavaScript?

This is my ISO formatted date. In here I want to get time like "11:00" by JavaScript.
I used this method:
new Date(Mydate).toLocaleString();
But it gave time as "16:30". Is there any format or method to do that in JavaScript? How can I get only time of that time zone.
var Mydate = "2012-10-16T11:00:28.556094Z";
Output will be the "11:00"
Modern approach, using ECMAScript Internationalization API built in to Node.js and most modern browsers:
const myDate = "2012-10-16T11:00:28.556094Z";
const time = new Date(myDate).toLocaleTimeString('en',
{ timeStyle: 'short', hour12: false, timeZone: 'UTC' });
// Output: "11:00"
Older approach, using moment.js:
var myDate = "2012-10-16T11:00:28.556094Z";
var time = moment.utc(myDate).format("HH:mm");
// Output: "11:00"
Use this:
var date = new Date(Mydate);
var time = ConvertNumberToTwoDigitString(date.getUTCHours()) +
":" + ConvertNumberToTwoDigitString(date.getUTCMinutes());
// Returns the given integer as a string and with 2 digits
// For example: 7 --> "07"
function ConvertNumberToTwoDigitString(n) {
return n > 9 ? "" + n : "0" + n;
}
Try this, I forget where I got this:
// --- Date ---
// convert ISO 8601 date string to normal JS Date object
// usage: (new Date()).setISO8601( "ISO8601 Time" )
Date.prototype.setISO8601 = function(string) {
var d, date, offset, regexp, time;
regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
d = string.match(new RegExp(regexp));
offset = 0;
date = new Date(d[1], 0, 1);
if (d[3]) date.setMonth(d[3] - 1);
if (d[5]) date.setDate(d[5]);
if (d[7]) date.setHours(d[7]);
if (d[8]) date.setMinutes(d[8]);
if (d[10]) date.setSeconds(d[10]);
if (d[12]) date.setMilliseconds(Number("0." + d[12]) * 1000);
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= (d[15] === '-' ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = Number(date) + (offset * 60 * 1000);
return this.setTime(Number(time));
};
Try this to grab the time from ISO date.
let Mydate = '2012-10-16T11:00:28.556094Z';
let result = Mydate .match(/\d\d:\d\d/);
console.log(result[0]);
The output will be,
11:00
be aware that older implementation of the toLocaleTimeString can behave differently depending on the browser's implementation.
Date: 2021-September-09
The locales and options arguments customize the behavior of the
function and let applications specify which language formatting
conventions should be used. In older implementations that ignore the
locales and options arguments, the locales and the form of the string
returned will be entirely implementation-dependent.
The implementation I recently used:
function getTimeFromISODateString(isoDateString) {
const date = new Date(isoDateString);
const hours = `0${date.getUTCHours()}`.slice(-2);
const minutes = `0${date.getUTCMinutes()}`.slice(-2);
const seconds = `0${date.getUTCSeconds()}`.slice(-2);
return `${hours}:${minutes}:${seconds}`;
}
This answer failed for me for any time of 00:34 as it got changed to 24:34
const time = new Date(myDate).toLocaleTimeString('en',
{ timeStyle: 'short', hour12: false, timeZone: 'UTC' });
It would seem this is a better solution, at least for me.
new Date(value).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
Source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString

Get String in YYYYMMDD format from JS date object?

I'm trying to use JS to turn a date object into a string in YYYYMMDD format. Is there an easier way than concatenating Date.getYear(), Date.getMonth(), and Date.getDay()?
Altered piece of code I often use:
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
var date = new Date();
date.yyyymmdd();
I didn't like adding to the prototype. An alternative would be:
var rightNow = new Date();
var res = rightNow.toISOString().slice(0,10).replace(/-/g,"");
<!-- Next line is for code snippet output only -->
document.body.innerHTML += res;
You can use the toISOString function :
var today = new Date();
today.toISOString().substring(0, 10);
It will give you a "yyyy-mm-dd" format.
Moment.js could be your friend
var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');
new Date('Jun 5 2016').
toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');
// => '2016-06-05'
If you don't need a pure JS solution, you can use jQuery UI to do the job like this :
$.datepicker.formatDate('yymmdd', new Date());
I usually don't like to import too much libraries. But jQuery UI is so useful, you will probably use it somewhere else in your project.
Visit http://api.jqueryui.com/datepicker/ for more examples
This is a single line of code that you can use to create a YYYY-MM-DD string of today's date.
var d = new Date().toISOString().slice(0,10);
I don't like modifying native objects, and I think multiplication is clearer than the string padding the accepted solution.
function yyyymmdd(dateIn) {
var yyyy = dateIn.getFullYear();
var mm = dateIn.getMonth() + 1; // getMonth() is zero-based
var dd = dateIn.getDate();
return String(10000 * yyyy + 100 * mm + dd); // Leading zeros for mm and dd
}
var today = new Date();
console.log(yyyymmdd(today));
Fiddle: http://jsfiddle.net/gbdarren/Ew7Y4/
In addition to o-o's answer I'd like to recommend separating logic operations from the return and put them as ternaries in the variables instead.
Also, use concat() to ensure safe concatenation of variables
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear();
var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
return "".concat(yyyy).concat(mm).concat(dd);
};
Date.prototype.yyyymmddhhmm = function() {
var yyyymmdd = this.yyyymmdd();
var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
return "".concat(yyyymmdd).concat(hh).concat(min);
};
Date.prototype.yyyymmddhhmmss = function() {
var yyyymmddhhmm = this.yyyymmddhhmm();
var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds();
return "".concat(yyyymmddhhmm).concat(ss);
};
var d = new Date();
document.getElementById("a").innerHTML = d.yyyymmdd();
document.getElementById("b").innerHTML = d.yyyymmddhhmm();
document.getElementById("c").innerHTML = d.yyyymmddhhmmss();
<div>
yyyymmdd: <span id="a"></span>
</div>
<div>
yyyymmddhhmm: <span id="b"></span>
</div>
<div>
yyyymmddhhmmss: <span id="c"></span>
</div>
Local time:
var date = new Date();
date = date.toJSON().slice(0, 10);
UTC time:
var date = new Date().toISOString();
date = date.substring(0, 10);
date will print 2020-06-15 today as i write this.
toISOString() method returns the date with the ISO standard which is YYYY-MM-DDTHH:mm:ss.sssZ
The code takes the first 10 characters that we need for a YYYY-MM-DD format.
If you want format without '-' use:
var date = new Date();
date = date.toJSON().slice(0, 10).split`-`.join``;
In .join`` you can add space, dots or whatever you'd like.
Plain JS (ES5) solution without any possible date jump issues caused by Date.toISOString() printing in UTC:
var now = new Date();
var todayUTC = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
return todayUTC.toISOString().slice(0, 10).replace(/-/g, '');
This in response to #weberste's comment on #Pierre Guilbert's answer.
// UTC/GMT 0
document.write('UTC/GMT 0: ' + (new Date()).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812013509
// Client local time
document.write('<br/>Local time: ' + (new Date(Date.now()-(new Date()).getTimezoneOffset() * 60000)).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812113509
Another way is to use toLocaleDateString with a locale that has a big-endian date format standard, such as Sweden, Lithuania, Hungary, South Korea, ...:
date.toLocaleDateString('se')
To remove the delimiters (-) is just a matter of replacing the non-digits:
console.log( new Date().toLocaleDateString('se').replace(/\D/g, '') );
This does not have the potential error you can get with UTC date formats: the UTC date may be one day off compared to the date in the local time zone.
var someDate = new Date();
var dateFormated = someDate.toISOString().substr(0,10);
console.log(dateFormated);
dateformat is a very used package.
How to use:
Download and install dateformat from NPM. Require it in your module:
const dateFormat = require('dateformat');
and then just format your stuff:
const myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');
Shortest
.toJSON().slice(0,10).split`-`.join``;
let d = new Date();
let s = d.toJSON().slice(0,10).split`-`.join``;
console.log(s);
Working from #o-o's answer this will give you back the string of the date according to a format string. You can easily add a 2 digit year regex for the year & milliseconds and the such if you need them.
Date.prototype.getFromFormat = function(format) {
var yyyy = this.getFullYear().toString();
format = format.replace(/yyyy/g, yyyy)
var mm = (this.getMonth()+1).toString();
format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
var dd = this.getDate().toString();
format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
var hh = this.getHours().toString();
format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
var ii = this.getMinutes().toString();
format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
var ss = this.getSeconds().toString();
format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
return format;
};
d = new Date();
var date = d.getFromFormat('yyyy-mm-dd hh:ii:ss');
alert(date);
I don't know how efficient that is however, especially perf wise because it uses a lot of regex. It could probably use some work I do not master pure js.
NB: I've kept the predefined class definition but you might wanna put that in a function or a custom class as per best practices.
A little variation for the accepted answer:
function getDate_yyyymmdd() {
const date = new Date();
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2,'0');
const dd = String(date.getDate()).padStart(2,'0');
return `${yyyy}${mm}${dd}`
}
console.log(getDate_yyyymmdd())
This guy here => http://blog.stevenlevithan.com/archives/date-time-format wrote a format() function for the Javascript's Date object, so it can be used with familiar literal formats.
If you need full featured Date formatting in your app's Javascript, use it. Otherwise if what you want to do is a one off, then concatenating getYear(), getMonth(), getDay() is probably easiest.
Little bit simplified version for the most popular answer in this thread https://stackoverflow.com/a/3067896/5437379 :
function toYYYYMMDD(d) {
var yyyy = d.getFullYear().toString();
var mm = (d.getMonth() + 101).toString().slice(-2);
var dd = (d.getDate() + 100).toString().slice(-2);
return yyyy + mm + dd;
}
You can simply use This one line code to get date in year
var date = new Date().getFullYear() + "-" + (parseInt(new Date().getMonth()) + 1) + "-" + new Date().getDate();
How about Day.js?
It's only 2KB, and you can also dayjs().format('YYYY-MM-DD').
https://github.com/iamkun/dayjs
Use padStart:
Date.prototype.yyyymmdd = function() {
return [
this.getFullYear(),
(this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based
this.getDate().toString().padStart(2, '0')
].join('-');
};
This code is fix to Pierre Guilbert's answer:
(it works even after 10000 years)
YYYYMMDD=new Date().toISOString().slice(0,new Date().toISOString().indexOf("T")).replace(/-/g,"")
Answering another for Simplicity & readability.
Also, editing existing predefined class members with new methods is not encouraged:
function getDateInYYYYMMDD() {
let currentDate = new Date();
// year
let yyyy = '' + currentDate.getFullYear();
// month
let mm = ('0' + (currentDate.getMonth() + 1)); // prepend 0 // +1 is because Jan is 0
mm = mm.substr(mm.length - 2); // take last 2 chars
// day
let dd = ('0' + currentDate.getDate()); // prepend 0
dd = dd.substr(dd.length - 2); // take last 2 chars
return yyyy + "" + mm + "" + dd;
}
var currentDateYYYYMMDD = getDateInYYYYMMDD();
console.log('currentDateYYYYMMDD: ' + currentDateYYYYMMDD);
[day,,month,,year]= Intl.DateTimeFormat(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date()),year.value+month.value+day.value
or
new Date().toJSON().slice(0,10).replace(/\/|-/g,'')
From ES6 onwards you can use template strings to make it a little shorter:
var now = new Date();
var todayString = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;
This solution does not zero pad. Look to the other good answers to see how to do that.
I usually use the code below when I need to do this.
var date = new Date($.now());
var dateString = (date.getFullYear() + '-'
+ ('0' + (date.getMonth() + 1)).slice(-2)
+ '-' + ('0' + (date.getDate())).slice(-2));
console.log(dateString); //Will print "2015-09-18" when this comment was written
To explain, .slice(-2) gives us the last two characters of the string.
So no matter what, we can add "0" to the day or month, and just ask for the last two since those are always the two we want.
So if the MyDate.getMonth() returns 9, it will be:
("0" + "9") // Giving us "09"
so adding .slice(-2) on that gives us the last two characters which is:
("0" + "9").slice(-2)
"09"
But if date.getMonth() returns 10, it will be:
("0" + "10") // Giving us "010"
so adding .slice(-2) gives us the last two characters, or:
("0" + "10").slice(-2)
"10"
It seems that mootools provides Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date
I'm not sure if it worth including just for this particular task though.
If you don't mind including an additional (but small) library, Sugar.js provides lots of nice functionality for working with dates in JavaScript.
To format a date, use the format function:
new Date().format("{yyyy}{MM}{dd}")

Categories

Resources