Convert yyyy-MM-dd to MM/dd/yyyy in javascript - 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));

Related

convert month-day-year into day-month-year using javascript

I'm trying to convert a MM/DD/YYYY date to a long date. So for example, 02/16/2020 would convert to something like 16/02/2020.
Is there a way to make this date conversion accurately?
You need to specify the original format of the time, and then convert it to a new format.
const date = "02/16/2020";
alert(moment(date, "MM/DD/YYYY").format('DD/MM/YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Use moment for date formatting:
Sample Code:
moment('02/16/2020').format('16/02/2020');
You can play with date by moment.js. It is very useful tool for javascript developer.
Momemet Js Document
For dynamic value:
moment(yourDate, 'MM/DD/YYYY').format('DD/MM/YYYY');
Here, yourDate is your dynamic value date.
check this. its work.
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 [day,month,year].join('/');
}
document.getElementById('res').innerHTML = formatDate('02/16/2020') ;
<div id="res">res</div>
2 || 1 liners ?
var src = '02/16/2020'
var a = src.split('/');
console.log(a.concat(a.splice(0, 2)).join('/'));
console.log(src.replace(/(\d+)\/(\d+)\/(\d+)/, '$3/$1/$2'));
If you want a conversion just between the exact formats you have mentioned:
function dfConvert(f) {
var farr = f.split("/");
return `${farr[1]}/${farr[0]}/${farr[2]}`;
}
var input = "02/16/2020";
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`);
If you want the actual date object and from that you want your mentioned format for some reason:
function toDate(f) {
var farr = f.split("/");
return new Date(parseInt(farr[2]), parseInt(farr[0])-1, parseInt(farr[1]))
}
function dfConvert(f) {
var d = toDate(f)
var day = d.getDate()
var month = (d.getMonth() + 1)
var year = d.getFullYear()
return `${((day.toString().length <= 1) ? "0": "")}${day}/${((month.toString().length <= 1) ? "0": "")}${month}/${year}`
}
var input = "02/16/2020"
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`)
Hope it helps

Handling date strings with various length

I'm trying to convert dates with different formats to a unified format.
The data I get can be MM/DD/YYYY or M/DD/YYYY or MM/D/YYYY or M/D/YYYY.
As of now I can handle all except M/D/YYYY.
Does anyone know how to solve that?
EDIT: Realized I didn't clarify which format I try to get, it's DD/MM/YYYY
My code as it is (not sure if it's the most efficient way):
var str = "2/13/2016"; // MM/DD/YYYY
var day = str.substr(3,2);
var month = str.substr(0,2);
var year = str.substr(6,4);
if(month.indexOf('/') > -1){
month = month.replace('/','');
var newM = '0' + month;
day = str_date.substr(2,2);
return day + '-' + newM + '-' + year;
}
else if(day.indexOf('/') > -1){
day = day.replace('/','');
var newD = '0' + day;
year = str.substr(5,5);
return newD + '-' + month + '-' + year;
}
else {
return day + '-' + month + '-' + year;
}
Using toLocaleDateString() with en-GB locale
console.log(new Date("2/13/2016").toLocaleDateString('en-GB', {
year: 'numeric', month: '2-digit', day: '2-digit'
}))
One approach would be to split the input string by / into three substring parts, and then parse each part to a number via Number.parseInt(). The final step would be to format a result string based on the three parsed numbers.
In code that could look like this:
var dateA = "2/13/2016"; // MM/DD/YYYY
function parseDate(str) {
const parts = str.split('/').map(part => Number.parseInt(part));
const [month, day, year] = parts;
return `${day}-${month}-${year}`
}
/* M/D/YYYY case */
console.log(parseDate("2/3/2016"), "should equal 3-2-2016");
/* M/DD/YYYY case */
console.log(parseDate("2/03/2016"), "should equal 3-2-2016");
/* MM/D/YYYY case */
console.log(parseDate("02/3/2016"), "should equal 3-2-2016");
/* MM/DD/YYYY case */
console.log(parseDate("02/03/2016"), "should equal 3-2-2016");
You could use momentjs and it's ability to parse a date string in one of several possible formats and format the parsed date in to a specific format.
const dates = ['1/8/2019', '01/8/2019', '1/08/2019', '01/08/2019'],
dateFormats = ['M/D/YYYY', 'MM/D/YYYY', 'M/DD/YYYY', 'MM/DD/YYYY'];
const parsedDates = dates.map((s) =>
moment(s, dateFormats).format('DD-MM-YYYY')
);
console.log(parsedDates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js" integrity="sha256-H9jAz//QLkDOy/nzE9G4aYijQtkLt9FvGmdUTwBk6gs=" crossorigin="anonymous"></script>
look use this code
const arr="2/13/2016".split('/').map(ele=>parseInt(ele))
const [day,mounth,year]=arr;
then check the condition date is the less then 30 and mutch then or equal 1 for day
then check the condition date is the less then 12and mutch then or equal 1for munth
then check the condition date is the less then new Date().getFullYear() mutch then or equal and more then 1950 then this correct date
then const dateWant=${day}/${mounth}/${year};

How to get the date trimmed of exactly in the format of (dd/mm/yyyy) in the following implementation of my code using JavaScript

How to get the date trimmed of exactly in the format of (dd/mm/yyyy) in the following implementation of my code using JavaScript
<script type="text/javascript" language="javascript">
function disptextbox() {
var d = new Date();
var x = document.getElementById("ddlweeklist").value;
switch (x)
{
case "1":
document.getElementById("txtstart").value = d.toDateString();
document.getElementById("Txtend").value = d.toDateString();
break;
case "2":
var firstday = new Date(d.setDate(d.getDate() - d.getDay()));
var lastday = new Date(d.setDate(d.getDate() - d.getDay() + 6));
document.getElementById("txtstart").value= firstday.toDateString();
document.getElementById("Txtend").value = lastday.toDateString();
break;
case "3":
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
document.getElementById("txtstart").value = firstDay.toDateString();
document.getElementById("Txtend").value = lastDay.toDateString();
break;
case "4":
var firstd = new Date(d.getFullYear(), 0, 1);
var lastd = new Date(d.getFullYear(), 11, 31);
document.getElementById("txtstart").value = firstd.toDateString();
document.getElementById("Txtend").value = lastd.toDateString();
break;
}
}
</script>
in this code of implementation I want the date format to be in dd/mm/yyyy format ...I will be glad if any one help me over this this function call occurs on the drop down change especially...I am ok with functionality of the code but not comfortable in handling with DATE FUNCTIONS...
so please suggest me where I can get good examples for implementing date functions...in javascript
You can do this if you want dd/mm/yyyy format date:
new Date().toISOString().substr(0,10).replace(/(\d{4})-(\d{2})-(\d{2})/g,"$3/$2/$1");
I've written a couple of prototypes for dates than you may find useful:
Date.prototype.dateStr=function(split){
split=split===undefined?"-":split;
var output=parseInt(parseInt(this.getMonth())+1).toString().toLength(2);
output+=split;
output+=this.getDate().toString().toLength(2);
output+=split;
output+=this.getFullYear().toString().toLength(4);
return output;
}
Date.prototype.FOM=function(){
return new Date(this.getFullYear(),this.getMonth(),1);
}
String.prototype.toLength=function(len,fill){
fill=fill===undefined?"0":fill;
var outStr=this.toString();
while (outStr.length<parseInt(len)){
outStr=fill+outStr;
}
return outStr;
}
Technically, the 3rd one is a string prototype, but whatever. new Date().FOM() will give you a javascript date object for the first day of whatever month you pass it. new Date().dateStr("/") will give you a string - mm/dd/yyyy format - with separators as whatever you pass it, default "-".
That last one will take a string and make it a certain length by prepending the 'fill' - default '0'.
You could try with this function:
function toDateString(mydate) {
var day = mydate.getDate();
var month = mydate.getMonth();
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
return day + '/' + month + '/' + mydate.getYear();
}
You could then use it this way:
alert(toDateString(firstday)); // I'm using alert just for demonstration purposes
Here is a DEMO you could fiddle with.
EDITED: Learning from #Helpful's answer below, my above function could be used as a prototype to better fit the way you wrote up your code like this:
Date.prototype.toDateString=function() {
var day = this.getDate();
var month = this.getMonth();
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
return day + '/' + month + '/' + this.getYear();
}
so you could call it this way:
alert(thedate.toDateString()); // This is how you used it, if I understood it well.
Here is a DEMO of that.
Pass any data format
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
hope this will help you sure.....

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.

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