javascript date to string

JavascriptStringDate

Javascript Problem Overview


Here is what I need to do.

Get Date, convert to string and pass it over to a third party utility. The response from the library will have date in string format as I passed it. So, I need to convert the date to string like 20110506105524 (YYYYMMDDHHMMSS)

function printDate() {
    var temp = new Date();
    var dateStr = temp.getFullYear().toString() + 
                  temp.getMonth().toString() + 
                  temp.getDate().toString() +
                  temp.getHours().toString() + 
                  temp.getMinutes().toString() + 
                  temp.getSeconds().toString();
                  
    debug (dateStr );
}

The problem with above is that for months 1-9, it prints one digit. How can I change it to print exactly 2 digits for month, date ...

Javascript Solutions


Solution 1 - Javascript

You will need to pad with "0" if its a single digit & note getMonth returns 0..11 not 1..12

function printDate() {
    var temp = new Date();
    var dateStr = padStr(temp.getFullYear()) +
                  padStr(1 + temp.getMonth()) +
                  padStr(temp.getDate()) +
                  padStr(temp.getHours()) +
                  padStr(temp.getMinutes()) +
                  padStr(temp.getSeconds());
    debug (dateStr );
}

function padStr(i) {
	return (i < 10) ? "0" + i : "" + i;
}

Solution 2 - Javascript

Relying on JQuery Datepicker, but it could be done easily:

var mydate = new Date();
$.datepicker.formatDate('yy-mm-dd', mydate);

Solution 3 - Javascript

use this polyfill https://github.com/UziTech/js-date-format

var d = new Date("1/1/2014 10:00 am");
d.format("DDDD 'the' DS 'of' MMMM YYYY h:mm TT");
//output: Wednesday the 1st of January 2014 10:00 AM

Solution 4 - Javascript

A little bit simpler using regex and toJSON().

var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]

Which at the time of writing gives you "20151111180924".

The good thing of using toJSON() is that everything comes already padded.

Solution 5 - Javascript

Maybe it is easier to convert the Date into the actual integer 20110506105524 and then convert this into a string:

function printDate() {
    var temp = new Date();
    var dateInt =
        ((((temp.getFullYear() * 100 + 
            temp.getMonth() + 1) * 100 + 
           temp.getDate()) * 100 +
          temp.getHours()) * 100 + 
         temp.getMinutes()) * 100 + 
        temp.getSeconds();

    debug ( '' + dateInt );  // convert to String
}

When temp.getFullYear() < 1000 the result will be one (or more) digits shorter.

Caution: this wont work with millisecond precision (i.e. 17 digits) since Number.MAX_SAFE_INTEGER is 9007199254740991 which is only 16 digits.

Solution 6 - Javascript

I like Daniel Cerecedo's answer using toJSON() and regex. An even simpler form would be:

var now = new Date();
var regex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).*$/;
var token_array = regex.exec(now.toJSON());
// [ "2017-10-31T02:24:45.868Z", "2017", "10", "31", "02", "24", "45" ]
var myFormat = token_array.slice(1).join('');
// "20171031022445"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKiranView Question on Stackoverflow
Solution 1 - JavascriptAlex K.View Answer on Stackoverflow
Solution 2 - JavascriptStéphaneView Answer on Stackoverflow
Solution 3 - JavascriptTony BrixView Answer on Stackoverflow
Solution 4 - JavascriptDaniel CerecedoView Answer on Stackoverflow
Solution 5 - JavascriptjammonView Answer on Stackoverflow
Solution 6 - JavascriptjammonView Answer on Stackoverflow