var date = \"2012-01-18T16:03\";
var date = new Date(date);
console.log(date.getMinutes());
console.log(date.getMinutes().length)
This returns 3.
Yikes these answers aren't great, even the top post upticked. Here y'go, cross-browser and cleaner int/string conversion. Plus my advice is don't use a variable name 'date' with code like date = Date(...)
where you're relying heavily on language case sensitivity (it works, but risky when you're working with server/browser code in different languages with different rules). So assuming the javascript Date in a var current_date
:
mins = ('0'+current_date.getMinutes()).slice(-2);
The technique is take the rightmost 2 characters (slice(-2))
of "0" prepended onto the string value of getMinutes()
. So:
"0"+"12" -> "012".slice(-2) -> "12"
and
"0"+"1" -> "01".slice(-2) -> "01"
.length
is undefined because getMinutes
is returning a number, not a string. numbers don't have a length
property. You could do
var m = "" + date.getMinutes();
to make it a string, then check the length (you would want to check for length === 1
, not 0).
Numbers don't have a length, but you can easily convert the number to a string, check the length and then prepend the 0 if it's necessary:
var strMonth = '' + date.getMinutes(); if (strMonth.length == 1) { strMonth = '0' + strMonth; }
Another option to get two digit minutes or hours.
var date = new Date("2012-01-18T16:03");
var minutes = date.toTimeString().slice(3, 5);
var hours = date.toTimeString().slice(0, 2);
Using ECMAScript Internationalization API, more info:
const twoDigitMinutes = date.toLocaleString('en-us', { minute: '2-digit' });
Elegant ES6 function to format a date into hh:mm:ss
:
const leadingZero = (num) => `0${num}`.slice(-2);
const formatTime = (date) =>
[date.getHours(), date.getMinutes(), date.getSeconds()]
.map(leadingZero)
.join(':');