Reputation: 15494
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()
?
Upvotes: 554
Views: 1517626
Reputation: 1045
const date = new Date()
console.log(date.toISOString().split('T')[0]) // 2022-12-27
Upvotes: 4
Reputation: 33
I've written a simple function, which can convert a Date
object to String
with date number, month number (with zero padding) and year number in customizable order. You can use it with any separator you like or leave this parameter empty to have no separator in output. Please, have a look.
function dateToString(date, $1, $2, $3, separator='') {
const dateObj = {
date: String(date.getDate()).padStart(2, '0'),
month: String(date.getMonth() + 1).padStart(2, '0'),
year: date.getFullYear()
};
return dateObj[$1] + separator + dateObj[$2] + separator + dateObj[$3];
}
const date = new Date();
const dateString1 = dateToString(date, 'year', 'month', 'date');
console.log(dateString1);
// Manipulate arguments order to get output you want
const dateString2 = dateToString(date, 'date', 'month', 'year', '-');
console.log(dateString2);
Upvotes: 1
Reputation: 4076
var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10).replaceAll("-", "");
// YearMonthDay
var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10).replaceAll("-", "");
console.log("YearMonthDay");
console.log(dateDisplay);
// Year-Month-Day
var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10);
console.log("Year-Month-Day");
console.log(dateDisplay);
// Year-Month-Day Hour:Minute:Second
var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 19).replace("T", " ");
console.log("Year-Month-Day Hour:Minute:Second");
console.log(dateDisplay);
// Year-Month-Day Hour-Minute-Second
var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 19).replace("T", " ").replaceAll(":", "-");
console.log("Year-Month-Day Hour-Minute-Second");
console.log(dateDisplay);
// ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ
var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON();
console.log("ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ");
console.log(dateDisplay);
Upvotes: 1
Reputation: 1053
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())
Upvotes: 8
Reputation: 651
A lot of answers here use the toisostring function. This function converts the time to zulu time before outputting, which may cause issues.
function datestring(time) {
return new Date(time.getTime() - time.getTimezoneOffset()*60000).toISOString().slice(0,10).replace(/-/g,"")
}
mydate = new Date("2018-05-03")
console.log(datestring(mydate))
The datestring function fixes the timezone issue, or even better you can avoid the whole issue by working in zulu time:
mydate = new Date("2018-05-03Z")
// mydate = new Date(Date.UTC(2018,5,3))
console.log(mydate.toISOString().slice(0,10).replace(/-/g,""))
Upvotes: 2
Reputation: 3698
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.
Upvotes: 6
Reputation: 652
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.
Upvotes: 31
Reputation: 92347
.toJSON().slice(0,10).split`-`.join``;
let d = new Date();
let s = d.toJSON().slice(0,10).split`-`.join``;
console.log(s);
Upvotes: 6
Reputation: 1318
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.
Upvotes: 3
Reputation: 1696
[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,'')
Upvotes: 5
Reputation: 7377
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');
Upvotes: 8
Reputation: 51
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('-');
};
Upvotes: 5
Reputation: 3460
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/
Upvotes: 38
Reputation: 26257
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>
Upvotes: 28
Reputation: 2705
You can use the toISOString
function :
var today = new Date();
today.toISOString().substring(0, 10);
It will give you a "yyyy-mm-dd" format.
Upvotes: 260
Reputation: 4811
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.
Upvotes: 3
Reputation:
Sure, you can build a specific function for each variation of date string representations. If you consider international date formats you wind up with dozens of specific functions with rediculous names and hard to distinguish.
There is no reasonable function that matches all formats, but there is a reasonable function composition that does:
const pipe2 = f => g => x =>
g(f(x));
const pipe3 = f => g => h => x =>
h(g(f(x)));
const invoke = (method, ...args) => o =>
o[method] (...args);
const padl = (c, n) => s =>
c.repeat(n)
.concat(s)
.slice(-n);
const inc = n => n + 1;
// generic format date function
const formatDate = stor => (...args) => date =>
args.map(f => f(date))
.join(stor);
// MAIN
const toYYYYMMDD = formatDate("") (
invoke("getFullYear"),
pipe3(invoke("getMonth")) (inc) (padl("0", 2)),
pipe2(invoke("getDate")) (padl("0", 2)));
console.log(toYYYYMMDD(new Date()));
Yes, this is a lot of code. But you can express literally every string date representation by simply changing the function arguments passed to the higher order function formatDate
. Everything is explicit and declarative i.e., you can almost read what's happening.
Upvotes: 1
Reputation: 41
I hope this function will be useful
function formatDate(dDate,sMode){
var today = dDate;
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
if (sMode+""==""){
sMode = "dd/mm/yyyy";
}
if (sMode == "yyyy-mm-dd"){
return yyyy + "-" + mm + "-" + dd + "";
}
if (sMode == "dd/mm/yyyy"){
return dd + "/" + mm + "/" + yyyy;
}
}
Upvotes: 0
Reputation: 1637
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.
Upvotes: 25
Reputation: 2564
How about Day.js?
It's only 2KB, and you can also dayjs().format('YYYY-MM-DD')
.
https://github.com/iamkun/dayjs
Upvotes: 4
Reputation: 2019
You can create yourself function as below
function toString(o, regex) {
try {
if (!o) return '';
if (typeof o.getMonth === 'function' && !!regex) {
let splitChar = regex.indexOf('/') > -1 ? '/' : regex.indexOf('-') > -1 ? '-' : regex.indexOf('.') > -1 ? '.' : '';
let dateSeparate = regex.split(splitChar);
let result = '';
for (let item of dateSeparate) {
let val = '';
switch (item) {
case 'd':
val = o.getDate();
break;
case 'dd':
val = this.date2Char(o.getDate());
break;
case 'M':
val = o.getMonth() + 1;
break;
case 'MM':
val = this.date2Char(o.getMonth() + 1);
break;
case 'yyyy':
val = o.getFullYear();
break;
case 'yy':
val = this.date2Char(o.getFullYear());
break;
default:
break;
}
result += val + splitChar;
}
return result.substring(0, result.length - 1);
} else {
return o.toString();
}
} catch(ex) { return ''; }
}
function concatDateToString(args) {
if (!args.length) return '';
let result = '';
for (let i = 1; i < args.length; i++) {
result += args[i] + args[0];
}
return result.substring(0, result.length - 1);
}
function date2Char(d){
return this.rightString('0' + d);
}
function rightString(o) {
return o.substr(o.length - 2);
}
Used:
var a = new Date();
console.log('dd/MM/yyyy: ' + toString(a, 'dd/MM/yyyy'));
console.log('MM/dd/yyyy: ' + toString(a, 'MM/dd/yyyy'));
console.log('dd/MM/yy: ' + toString(a, 'dd/MM/yy'));
console.log('MM/dd/yy: ' + toString(a, 'MM/dd/yy'));
Upvotes: 0
Reputation: 5177
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;
Upvotes: 397
Reputation: 2032
date-shortcode to the rescue!
const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYYMMDD}', new Date())
//=> '20180304'
Upvotes: 2
Reputation: 29
yyyymmdd=x=>(f=x=>(x<10&&'0')+x,x.getFullYear()+f(x.getMonth()+1)+f(x.getDate()));
alert(yyyymmdd(new Date));
Upvotes: 2
Reputation: 11344
Native Javascript:
new Date().toLocaleString('zu-ZA').slice(0,10).replace(/-/g,'');
Upvotes: 1
Reputation: 27395
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);
Upvotes: 4
Reputation: 132
<pre>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]));
var ampm = (hh >= 12) ? "PM" : "AM";
format = format.replace(/ampm/g, (ampm[1]?ampm:"0"+ampm[0]));
return format;
};
var time_var = $('#899_TIME');
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
var date = d.getFromFormat('dd-mm-yyyy hh:ii:ss:ampm');
time_var.text(date);
} </pre>
use the code and get the output like **26-07-2017 12:29:34:PM**
check the below link for your reference
https://parthiban037.wordpress.com/2017/07/26/date-and-time-format-in-oracle-apex-using-javascript/
Upvotes: -1
Reputation: 259
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();
Upvotes: 5
Reputation: 32788
var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');
Upvotes: 179
Reputation: 5307
If using AngularJs (up to 1.5) you can use the date filter:
var formattedDate = $filter('date')(myDate, 'yyyyMMdd')
Upvotes: 2