var date = new Date();
alert( date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + date.getDate()).slice(-2) + ("0" + date.getHours() ).slice(-2) + ("0" + date.getMinutes()).slice(-2) + ("0" + date.getSeconds()).slice(-2) );
edit
function pad2(n) { return n < 10 ? '0' + n : n }
var date = new Date();
alert( date.getFullYear().toString() + pad2(date.getMonth() + 1) + pad2( date.getDate()) + pad2( date.getHours() ) + pad2( date.getMinutes() ) + pad2( date.getSeconds() ) );
Answer from gurvinder372 on Stack OverflowVideos
var date = new Date();
alert( date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + date.getDate()).slice(-2) + ("0" + date.getHours() ).slice(-2) + ("0" + date.getMinutes()).slice(-2) + ("0" + date.getSeconds()).slice(-2) );
edit
function pad2(n) { return n < 10 ? '0' + n : n }
var date = new Date();
alert( date.getFullYear().toString() + pad2(date.getMonth() + 1) + pad2( date.getDate()) + pad2( date.getHours() ) + pad2( date.getMinutes() ) + pad2( date.getSeconds() ) );
Here's my (ES5 safe) method to add the YYYYMMDDHHMMSS() function to any Date object.
On older browsers, either shim Object.defineProperty or just add the inner function directly to Date.prototype:
Object.defineProperty(Date.prototype, 'YYYYMMDDHHMMSS', {
value: function() {
function pad2(n) { // always returns a string
return (n < 10 ? '0' : '') + n;
}
return this.getFullYear() +
pad2(this.getMonth() + 1) +
pad2(this.getDate()) +
pad2(this.getHours()) +
pad2(this.getMinutes()) +
pad2(this.getSeconds());
}
});
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/
[Addendum 12/2022]: Here's a library to format dates using Intl.DateTimeFormat.
[Addendum 01/2024]: And here is a (ES-)Date manipulation library
Try something like this
var d = new Date,
dformat = [d.getMonth()+1,
d.getDate(),
d.getFullYear()].join('/')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
If you want leading zero's for values < 10, use this number extension
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3'
Applied to the previous code:
var d = new Date,
dformat = [(d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/') +' ' +
[d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'
See this code in [jsfiddle][1]
[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.
const dt = new Date();
const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);
console.log(`${
padL(dt.getMonth()+1)}/${
padL(dt.getDate())}/${
dt.getFullYear()} ${
padL(dt.getHours())}:${
padL(dt.getMinutes())}:${
padL(dt.getSeconds())}`
);
You can always format a date by extracting the parts and combine them using string functions in desired order:
function formatDate(date) {
let datePart = [
date.getMonth() + 1,
date.getDate(),
date.getFullYear()
].map((n, i) => n.toString().padStart(i === 2 ? 4 : 2, "0")).join("/");
let timePart = [
date.getHours(),
date.getMinutes(),
date.getSeconds()
].map((n, i) => n.toString().padStart(2, "0")).join(":");
return datePart + " " + timePart;
}
let date = new Date();
console.log("%o => %s", date, formatDate(date));
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.
If using AngularJs (up to 1.5) you can use the date filter:
var formattedDate = $filter('date')(myDate, 'yyyyMMdd')
The code looks good and works well. Since it provides a useful bit of work, you should convert it into a function. Then you can copy that function to another program if you need so.
function yyyymmdd() {
var x = new Date();
var y = x.getFullYear().toString();
var m = (x.getMonth() + 1).toString();
var d = x.getDate().toString();
(d.length == 1) && (d = '0' + d);
(m.length == 1) && (m = '0' + m);
var yyyymmdd = y + m + d;
return yyyymmdd;
}
To make this code a little easier to read, you should rename x to now.
You could also omit the calls to toString(), which makes the code a little shorter. Plus, you should introduce the variables mm and dd, so that you don't reassign to the d and m variables. This is a generally useful pattern, because when stepping through the code you can always look at the variable definition to see how it was computed. This is not possible for variables that change their value during execution.
The modified code looks like this:
function yyyymmdd() {
var now = new Date();
var y = now.getFullYear();
var m = now.getMonth() + 1;
var d = now.getDate();
var mm = m < 10 ? '0' + m : m;
var dd = d < 10 ? '0' + d : d;
return '' + y + mm + dd;
}
Or, you could inline the last few lines:
function yyyymmdd() {
var now = new Date();
var y = now.getFullYear();
var m = now.getMonth() + 1;
var d = now.getDate();
return '' + y + (m < 10 ? '0' : '') + m + (d < 10 ? '0' : '') + d;
}
That last variant is harder to read though, therefore I prefer the previous one.
Another possibility is to define a helper function that produces a two-digit string:
function yyyymmdd() {
function twoDigit(n) { return (n < 10 ? '0' : '') + n; }
var now = new Date();
return '' + now.getFullYear() + twoDigit(now.getMonth() + 1) + twoDigit(now.getDate());
}
For getting the 0 padded date and month values, I generally follow this approach:
let d = ('0' + x.getDate()).substring(-2)
However, the Date objects have a .toISOString method, which returns the string in YYYY-MM-DDTHH:MM:SSZ format, which you can split on T and then replace - (or vice-versa):
formatted_date = (new Date()).toISOString().replace(/-/g, '').split('T')[0]
// same as (new Date()).toISOString().split('T')[0].replace(/-/g, '')
As new Date().toISOString() will return current UTC time, to get local time in ISO String format we have to get time from new Date() function like the following method
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0]);
You can use moment.js library to achieve this.
Try:
var moment = require('moment')
let dateNow = moment().format('YYYY-MM-DDTHH:MM:SS')