Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript date to string

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 ...

like image 308
Kiran Avatar asked Sep 27 '22 23:09

Kiran


People also ask

Is Date in JS a string?

JavaScript Date toString()The toString() method returns a date object as a string.

What date format is DD MMM YYYY JavaScript?

There is no native format in JavaScript for” dd-mmm-yyyy”. To get the date format “dd-mmm-yyyy”, we are going to use regular expression in JavaScript.


2 Answers

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;
}
like image 66
Alex K. Avatar answered Oct 09 '22 07:10

Alex K.


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

var mydate = new Date();
$.datepicker.formatDate('yy-mm-dd', mydate);
like image 39
Stéphane Avatar answered Oct 09 '22 07:10

Stéphane