Get String in YYYYMMDD format from JS date object? - javascript
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}")
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));
How can I convert timestamp to date format yyyy-MM-dd'T'HH:mm:ssXXX?
I would like to know if there's a way to convert a timestamp to yyyy-MM-dd'T'HH:mm:ssXXX date format? I can convert it to ISO using toISOString but it add Z at the end of the string. Thank you.
var d = new Date(); var datestring = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + "-T " + d.getHours() + ":" + d.getMinutes();
If you really do not want to use an external library like moment.js (which i would strongly recommend), as you stated in your comment, you will have to implement a function for that yourself, as regular javascript does not provide a function for this (as far as i know). You can create an object of javascripts built-in Date class from a unix timestamp by using var unixTimestamp = 1566394163; //multiply with 1000 as Date expects milliseconds var date = new Date(unixTimestamp * 1000); Then you could build the output string yourself, by using something along this var dateString = ""; dateString += date.getUTCFullYear()+"-"; dateString += date.getUTCMonth()+"-"; dateString += ... On the other hand, if the Z at the end of the string is the only thing that bothers you about the format provided by toISOString() as a workaround you could use its output and remove the last character of it var dateString = date.toISOString(); var newDateString = dateString.substr(0, dateString.length -1);
Please try using below code to convert timestamp to date format. var date = new Date(timestamp*1000); var year = date.getFullYear(); var month = months_arr[date.getMonth()]; var day = date.getDate(); var hours = date.getHours(); var minutes = "0" + date.getMinutes(); var seconds = "0" + date.getSeconds(); Display date time in any format you want.
Convert ISO 8061 to YYYY/MM/DD?
I have this ISO 8061 2017-05-03T06:31:46.687123+00:00 which I want to convert it to YYYY-MM-DD using D3. Any help will be appreciated.
check out momentjs and specifically the format function: https://momentjs.com/docs/#/displaying/ You can then write something like: moment("2017-05-03T06:31:46.687123+00:00").format("YYYY-MM-DD");
Since you want to use d3.js... be careful with the version you are using because there has been a small change to the name of the function: with v.3.4.11 use d3.time.format("%Y-%m-%d") with v.4.9.1 use d3.timeFormat("%Y-%m-%d") 3.4.11 your_date = new Date('2017-05-03T06:31:46.687123+00:00') var formatTime = d3.time.format("%Y-%m-%d"); new_date = formatTime( your_date ); // 2017-05-03 console.log(new_date); <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 4.9.1 your_date = new Date('2017-05-03T06:31:46.687123+00:00') var formatTime = d3.timeFormat("%Y-%m-%d"); new_date = formatTime( your_date ); // 2017-05-03 console.log(new_date); <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>
i think this code will work but i didnt test it yet can you test it and give me a feedback please date = new Date('2017-05-03T06:31:46.687123+00:00'); 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 can also crop the date dat.toISOString().substring(0, 10)
When I found this library - https://date-fns.org/ I prefer it instead of moment.js. Date-fns is modular, and your could import only one method. This allows significantly reduced bundle size in compare with not modular moment.js: import format from 'date-fns/format'; format('2017-05-03T06:31:46.687123+00:00', 'YYYY-MM-DD');
Javascript format date
I have a date string which coming from the db as follows /Date(1469167371657)/ Is there any way to convert this date to following format using javascript MM/DD/YYYY HH:MM I've searched a lot but unble to find a solution
In plain javascript you have to write your own function for string format a date, for example for your string format: var date = new Date(1469167371657); function stringDate(date) { var mm = date.getMonth()+1; mm = (mm<10?"0"+mm:mm); var dd = date.getDate(); dd = (dd<10?"0"+dd:dd); var hh = date.getHours(); hh = (hh<10?"0"+hh:hh); var min = date.getMinutes(); min = (min<10?"0"+min:min); return mm+'/'+dd+'/'+date.getFullYear()+" "+hh+":"+min; } console.log(stringDate(date)); drier code version var date = new Date(1469167371657); function stringDate(date) { return ("0" + (date.getMonth() + 1)).slice(-2)+'/' +("0" + date.getDate()).slice(-2)+'/' +date.getFullYear()+" " +("0" + date.getHours()).slice(-2)+':' +("0" + date.getMinutes()).slice(-2) } console.log(stringDate(date));
with pure js you can do the folowing var d = new Date(); console.log(d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes())
You can use - http://momentjs.com/ and have it done like: moment(1469167371657).format('MM/DD/YYYY HH:MM')
You can do this with the following steps: 1) convert the timestamp to a date object. var timestamp = "/Date(1469167371657)/"; // However you want to save whatever comes from your database timestamp = timestamp.substr(timestamp.indexOf("(")+1); // gives 1469167371657)/ timestamp = timestamp.substr(0,timestamp.indexOf(")")); // gives 1469167371657 var d = new Date(timestamp); 2) set it to your format function leadZero(i) {if(i < 10) {return "0"+i;} return i;} // Simple function to convert 5 to 05 e.g. var time = leadZero(d.getMonth()+1)+"/"+leadZero(d.getDate())+"/"+d.getFullYear()+" "+leadZero(d.getHours())+":"+leadZero(d.getMinutes()); alert(time); Note: the date / timestamp you provided is too high for javascript to understand, so this example will not work correclty
I believe that number is milliseconds so to convert it to date, you would do this: var time = new Date().getTime(); var date = new Date(time); alert(date.toString()); // Wed Jan 12 2011 12:42:46 GMT-0800 (PST) var time=1469167371657; var date = new Date(time); alert(date.toString());
Convert input type text into date format
I have one input type text: <input type="text" id="policyholder-dob" name="policyholder-dob" /> I want to type number in this field in mm/dd/yyyy format: like 01/01/2014 This is my js code but its not working, what mistake have I made? function dateFormatter(date) { var formattedDate = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(); return formattedDate; } var nextduedate = $("#policyholder-dob").val(); var dateFormatDate = nextduedate.slice(0, 2); var dateFormatMonth = nextduedate.slice(2, 4); var dateFormatYear = nextduedate.slice(4, 8); var totalFormat = dateFormatMonth + '/' + dateFormatDate + '/' + dateFormatYear; var againNewDate = new Date(totalFormat); againNewDate.setDate(againNewDate.getDate() + 1); var todaydate = dateFormatter(againNewDate); $("#policyholder-dob").prop("value", todaydate); Any help will be really appreciated.
Thankfully, your input is consistently in this format: mm/dd/yyyy So you can convert it to a Date object through a custom function, such as: function stringToDate(str){ var date = str.split("/"), m = date[0], d = date[1], y = date[2], temp = []; temp.push(y,m,d); return (new Date(temp.join("-"))).toUTCString(); } Or: function stringToDate(str){ var date = str.split("/"), m = date[0], d = date[1], y = date[2]; return (new Date(y + "-" + m + "-" + d)).toUTCString(); } Etc.. Calling it is easy: stringToDate("12/27/1963"); And it will return the correct timestamp in GMT (so that your local timezone won't affect the date (EST -5, causing it to be 26th)): Fri, 27 Dec 1963 00:00:00 GMT //Late december Example There are various ways to accomplish this, this is one of them.
I'd suggest moment.js for date manipulation. You're going to run into a world of hurt if you're trying to add 1 to month. What happens when the month is December and you end up with 13 as your month. Let a library handle all of that headache for you. And you can create your moment date with the string that you pull from the val. You substrings or parsing. var d = moment('01/31/2014'); // creates a date of Jan 31st, 2014 var duration = moment.duration({'days' : 1}); // creates a duration object for 1 day d.add(duration); // add duration to date alert(d.format('MM/DD/YYYY')); // alerts 02/01/2014 Here's a fiddle showing it off.