Compatible date formats for browser [duplicate] - javascript

This question already has an answer here:
.toLocaleDateString() Not Working in Firefox
(1 answer)
Closed 7 years ago.
I am trying to display "dd-mm-yyyy" date format using the following method
document.getElementById('engStartDate').value=endDate.toLocaleDateString('en-IN',options);
But i am not getting the required format in chrome
Chrome : Jun 11, 2016
Firefox : 11-Jun-2016

It might not directly answer your question, but I suggest you give momentjs a try. It's a Javascript library that allows you to manipulate and format dates and has saved my hide more than once. In your case you would do something like
document.getElementById('engStartDate').value = moment(endDate).format('DD-MM-YYYY);

Date.prototype.toLocaleString doesn't take any arguments and the result is entirely implementation dependent.
If you want a particular format, you can use a library but it's not hard to write a simple function to output dd-mm-yyyy format:
function toDMY(d) {
function z(n){return (n<10?'0':'')+n}
return z(d.getDate()) + '-' + z(d.getMonth()+1) + '-' + d.getFullYear();
}
document.write(toDMY(new Date()));
There is also the ECMAScript Internationalization API 1.0 (ECMA-402) (also on MDN), however it's not well supported yet.

I strongly recommend you to do it manually or use a lib.
I write an example of formate data-time.
var datetimeFormat = function ( datetime, formatStr) {
var obj = null;
if (({}).toString.call(datetime) === '[object Date]') {
obj = datetime;
} else {
datetime = +datetime || 0;
datetime = datetime < +new Date() / 100 ? datetime * 1000 : datetime;
obj = new Date(datetime);
}
var str = formatStr;
var Week = ['Sun', 'Mon', 'Tue', 'Wen', 'Tur', 'Fri', 'Sat'];
str = str.replace(/yyyy|YYYY/, obj.getFullYear());
str = str.replace(/yy|YY/,('0' + obj.getYear() % 100).slice(-2));
var month = obj.getMonth() + 1;
str = str.replace(/MM/, ('0' + month).slice(-2));
str = str.replace(/M/g, month);
str = str.replace(/w|W/g, Week[obj.getDay()]);
str = str.replace(/dd|DD/, ('0' + obj.getDate()).slice(-2));
str = str.replace(/d|D/g, obj.getDate());
str = str.replace(/hh|HH/, ('0' + obj.getHours()).slice(-2));
str = str.replace(/h|H/g, obj.getHours());
str = str.replace(/mm/, ('0' + obj.getMinutes()).slice(-2));
str = str.replace(/m/g, obj.getMinutes());
str = str.replace(/ss|SS/, ('0' + obj.getSeconds()).slice(-2));
str = str.replace(/s|S/g, obj.getSeconds());
return str;
}
document.getElementById('engStartDate').value = datetimeFormat(new Date(), 'dd-MM-yyyy')
<input type='text' id='engStartDate'/>

Related

How to convert a date to string with time zone [duplicate]

This question already has answers here:
How to ISO 8601 format a Date with Timezone Offset in JavaScript?
(21 answers)
Closed 6 years ago.
In my database I must put a date time in ISO format with time zone. For example I have the following entry column:
17/02/2016 22:00:00 +01:00
I have a web service that accept a date (in JSON object) like this:
{
//...
"Start": "2016-02-17T22:00:00+01:00"
//...
}
Now in my javascript code i've tried:
var today = new Date();
var dateString = today.toISOString();
But the output of dateString is:
"2016-03-05T12:10:32.537Z"
How can I get a string like this:
"2016-03-05T13:10:32.537+01:00"
Thanks
I believe you can't obtain a local ISO 8601 format directly from a Date function. toISOString() gives you the time in UTC / GMT: 2016-03-05T12:10:32.537Z (that's what the Z in the end is for, it means UTC)
This is how you can do it by composing the string yourself:
var date = new Date(); // this is your input date
var offsetHours = -date.getTimezoneOffset() / 60;
var offsetMinutesForDisplay = Math.abs(-date.getTimezoneOffset() % 60);
var offsetHoursForDisplay = Math.floor(offsetHours) + (offsetHours < 0 && offsetMinutesForDisplay != 0 ? 1 : 0);
var isoOffset = (offsetHours >= 0 ? ("+" + fillDigit(offsetHoursForDisplay, true)) : fillDigit(offsetHoursForDisplay, true)) + ':' + fillDigit(offsetMinutesForDisplay, true);
document.getElementById('myDiv').innerHTML = date.getFullYear() + '-' + fillDigit(date.getMonth() + 1, true) + '-' + fillDigit(date.getDate(), true) + 'T' + fillDigit(date.getHours(), true) + ':' + fillDigit(date.getMinutes(), true) + ':' + fillDigit(date.getSeconds(), true) + isoOffset;
function fillDigit(value, withDigit) { // we want to display 04:00 instead of 4:00
if (value >= 0 && value < 10) {
return (withDigit ? "0" : " ") + value;
}
if (value > -10 && value < 0) {
return '-' + (withDigit ? "0" : " ") + (-value);
}
return value;
}
<div id='myDiv'></div>
You can check out http://currentmillis.com/?now for Javascript that will get you multiple formats
If you want a custom format you need format the date by yourself using Date object methods like:
date = new Date();
hour= date.getHours();
min= date.getMinutes();
sec= date.getSeconds();
time= hour+':'+min+':'+sec;
console.log(time)
This can be encapsulated in a function or in a object method for convenience.

Convert yyyy-MM-dd to MM/dd/yyyy in javascript

This might be a simple solution but I am stuck, basically I need convert an incoming yyyy-MM-dd to MM/dd/yyyy also, if incoming date is nil, then output should also be nil.
Incoming date could be of following format
2015-01-25 or nil
Output date shoud be
01/25/2015 or nil
I was trying one from the following link
Convert Date yyyy/mm/dd to MM dd yyyy but couldn't make it work.
Thanks for any help.
Forgot to mention, the incoming date which comes as nil is of the following format in an xml file
<Through_Date__c xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
So if I get the above format the output should be just be nil
The date toString function has some support for formatting. See this. And you also want to handle the undefined case which I took from here. So, for your case you can just do this:
function format(inputDate) {
var date = new Date(inputDate);
if (!isNaN(date.getTime())) {
// Months use 0 index.
return date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
}
}
EDIT: Addressing the comment
If the padding is important you just need to add that in:
var d = date.getDate().toString();
(d[1]?d:"0"+d[0])
I've made an update to the fiddle
Try using RegEx:
var format = function(input) {
var pattern = /(\d{4})\-(\d{2})\-(\d{2})/;
if (!input || !input.match(pattern)) {
return null;
}
return input.replace(pattern, '$2/$3/$1');
};
console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));
Using String#split and Array#join, push & shift:
var format = function(input) {
var array = (input || '').toString().split(/\-/g);
array.push(array.shift());
return array.join('/') || null;
};
console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));
if you wanna go ghetto style and use easily understandable code, and you dont care about using a date object, try this!
function changeDateFormat(inputDate){ // expects Y-m-d
var splitDate = inputDate.split('-');
if(splitDate.count == 0){
return null;
}
var year = splitDate[0];
var month = splitDate[1];
var day = splitDate[2];
return month + '\\' + day + '\\' + year;
}
var inputDate = '2015-01-25';
var newDate = changeDateFormat(inputDate);
console.log(newDate); // 01/25/2015
you can deal your javascript dates in various formats.
For dd/MM/yyyy you can use
var date = new Date().toLocalDateString()
or
var date = new Date('2021-07-28').toLocalDateString()
output: '28/07/2021'
For MM/dd/yyyy
var date = new Date().toLocaleDateString("en-US", { year: "numeric", month: "2-digit", day: "2-digit" })
or
var date = new Date('2021-07-28').toLocaleDateString("en-US", { year: "numeric", month: "2-digit", day: "2-digit" })
output: '07/28/2021'
Alternatively you can handle custom date formats using following date functions
let date = new Date()
let dateString = [
date.getMonth() + 1,
date.getDate(),
date.getFullYear(),
].join('/')
}
output: 07/28/2021
If your date has not yet been parsed from a string, you can simply rearrange its components:
var s = '2015-01-25';
if (s) {
s = s.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/, function(match,y,m,d) {
return m + '/' + d + '/' + y;
});
}
Thanks guys, I was able to do grab some ideas from all your posts and came up with this code which seems to working fine in my case
if((typeof inStr == 'undefined') || (inStr == null) ||
(inStr.length <= 0)) {
return '';
}
var year = inStr.substring(0, 4);
var month = inStr.substring(5, 7);
var day = inStr.substring(8, 10);
return month + '/' + day + '/' + year;
You can also try the method below using vanilla JS. I have converted the date to a string & parsed it to get the format you're looking for:
function tranformDate(strDate) {
let result = '';
if (date) {
let parts = date.split('-');
result = `${parts[1]}/${parts[2]}/${parts[0]}`;
}
return result;
}
let date = new Date().toISOString().split('T')[0];
console.log('raw date: ' + date);
console.log('formatted date: ' + tranformDate(date));

jQuery: Add 4 weeks to date in format dd-mm-yyyy

I have a string which has a date in the format: dd-mm-yyyy
How I can add 4 weeks to the string and then generate a new string using jQuery / Javascript?
I have
var d = new Date(current_date);
d.setMonth(d.getMonth() + 1);
current_date_new = (d.getMonth() + 1 ) + '-' + d.getDate() + '-' + d.getFullYear();
alert(current_date_new);
but it complains that the string provided is in the incorrect format
EDIT: After a bit of fiddling, here's the solution:
First, split the string to individual parts.
var inputString = "12-2-2005";
var dString = inputString.split('-');
Then, parse the string to a datetime object and add 28 days (4 weeks) to it.
var dt = new Date(dString[2],dString[1]-1,dString[0]);
dt.setDate(dt.getDate()+28);
Finally, you can output the date
var finalDate = dt.GetDate() + "-" + (dt.GetMonth()+1) + "-" + dt.GetYear();
This code should return 12-3-2005.
CAVEATS: It seems JavaScript's Date object takes 0-11 as the month field, hence the -1 and +1 to the month in the code.
EDIT2: To do padding, use this function:
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
and change your output to
var finalDate = pad(dt.GetDate(),2) + "-" + pad(dt.GetMonth()+1,2) + "-" + dt.GetYear();
Check the updated fiddle.
There is no need to convert to mm-dd-yyyy, simple split string by the minus sign and create new Date object with the following code:
var string = '12-02-2012';
var split = string.split('-');
var date = Date(split[2],parseInt(split[1])-1,parseInt(split[0])+1)
date.setDate(date.getDate() + 28);
var fourWeeksLater = date.getDay() + "-"+date.getMonth() +"-"+date.getYear();
This should be working:
var formattedDate = '01-01-2012',
dateTokens = formattedDate.split('-'),
dt = new Date(dateTokens[2], parseInt( dateTokens[1], 10 ) - 1, dateTokens[0]), // months are 0 based, so need to add 1
inFourWeeks = new Date( dt.getTime() + 28 * 24 * 60 * 60 * 1000 );
jsfiddle: http://jsfiddle.net/uKDJP/
Edit:
Using Globalize you can format inFourWeeks:
Globalize.format( inFourWeeks, 'dd-MM-yyyy' ) // outputs 29-01-2012
Instead of writing your own parser for dates, I would use moment.js.
To parse your date:
var date = moment('14-06-2012', 'DD-MM-YYYY');
To add 4 weeks to it:
date.add('weeks', 4);
Or in one go:
var date = moment('14-06-2012', 'DD-MM-YYYY').add('weeks', 4);
And convert it to string:
var dateString = date.format('DD-MM-YYYY');

Convert datetime to valid JavaScript date [duplicate]

This question already has answers here:
Convert date from string in javascript
(4 answers)
Closed 3 years ago.
I have a datetime string being provided to me in the following format:
yyyy-MM-dd HH:mm:ss
2011-07-14 11:23:00
When attempting to parse it into a JavaScript date() object it fails. What is the best way to convert this into a format that JavaScript can understand?
The answers below suggest something like
var myDate = new Date('2011-07-14 11:23:00');
Which is what I was using. It appears this may be a browser issue. I've made a http://jsfiddle.net/czeBu/ for this. It works OK for me in Chrome. In Firefox 5.0.1 on OS X it returns Invalid Date.
This works everywhere including Safari 5 and Firefox 5 on OS X.
UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below
var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));
console.log(date_test);
FIDDLE
One can use the getmonth and getday methods to get only the date.
Here I attach my solution:
var fullDate = new Date(); console.log(fullDate);
var twoDigitMonth = fullDate.getMonth() + "";
if (twoDigitMonth.length == 1)
twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + "";
if (twoDigitDate.length == 1)
twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
Just use Date.parse() which returns a Number, then use new Date() to parse it:
var thedate = new Date(Date.parse("2011-07-14 11:23:00"));
Use:
enter code var moment = require('moment')
var startDate = moment('2013-5-11 8:73:18', 'YYYY-M-DD HH:mm:ss')
Moment.js works very well. You can read more about it here.
function ConvertDateFromDiv(divTimeStr) {
//eg:-divTimeStr=18/03/2013 12:53:00
var tmstr = divTimeStr.toString().split(' '); //'21-01-2013 PM 3:20:24'
var dt = tmstr[0].split('/');
var str = dt[2] + "/" + dt[1] + "/" + dt[0] + " " + tmstr[1]; //+ " " + tmstr[1]//'2013/01/20 3:20:24 pm'
var time = new Date(str);
if (time == "Invalid Date") {
time = new Date(divTimeStr);
}
return time;
}
You can use moment.js for that, it will convert DateTime object into valid Javascript formated date:
moment(DateOfBirth).format('DD-MMM-YYYY'); // put format as you want
Output: 28-Apr-1993
Hope it will help you :)
new Date("2011-07-14 11:23:00"); works fine for me.
You can use get methods:
var fullDate = new Date();
console.log(fullDate);
var twoDigitMonth = fullDate.getMonth() + "";
if (twoDigitMonth.length == 1)
twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + "";
if (twoDigitDate.length == 1)
twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);

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