Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  116] [ 5]  / answers: 1 / hits: 115642  / 13 Years ago, fri, may 6, 2011, 12:00:00

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


More From » string

 Answers
6

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




function printDate() {
const temp = new Date();
const pad = (i) => (i < 10) ? 0 + i : + i;

return temp.getFullYear() +
pad(1 + temp.getMonth()) +
pad(temp.getDate()) +
pad(temp.getHours()) +
pad(temp.getMinutes()) +
pad(temp.getSeconds());
}

console.log(printDate());




[#92364] Thursday, May 5, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madalyngriseldas

Total Points: 167
Total Questions: 92
Total Answers: 85

Location: Iceland
Member since Sat, Sep 17, 2022
2 Years ago
;