Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
129
rated 0 times [  133] [ 4]  / answers: 1 / hits: 25619  / 14 Years ago, thu, july 22, 2010, 12:00:00

Looking for a creative way to be sure values that come from the getHours, getMinutes, and getSeconds() method for the javascript Date object return 06 instead of 6 (for example). Are there any parameters that I don't know about? Obviously I could write a function that does it by checking the length and prepending a 0 if need be, but I thought there might be something more streamlined than that.



Thanks.


More From » date

 Answers
100

Update: ECMAScript 2017 (ECMA-262)



padStart has been added to pad the beginning of a string with another string, where the first value is the length it should be and the second value being what to pad it with.



For example:



let d = new Date()
let h = `${d.getHours()}`.padStart(2, '0')
let m = `${d.getMinutes()}`.padStart(2, '0')
let s = `${d.getSeconds()}`.padStart(2, '0')

let displayDate = h + : + m + : + s
// Possible Output: 09:01:34





Pre-ECMAScript 2017



As far as I know, there's not. And I do this all the time for converting dates to the XML dateTime format.



It's also important to note that those methods you list return a number, not a string.



You can, of course, add these yourself by modifying Date.prototype.



Date.prototype.getHoursTwoDigits = function()
{
var retval = this.getHours();
if (retval < 10)
{
return (0 + retval.toString());
}
else
{
return retval.toString();
}
}

var date = new Date();
date.getHoursTwoDigits();

[#96140] Tuesday, July 20, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;