rensa rensa - 25 days ago 5
Javascript Question

Moment.js formats locally until I specify the format

I need to set a

datetime-local
picker's default value to the current local time. Native JS seems to output in local time by default:

new Date($.now()); // "Sat Nov 12 2016 22:36:52 GMT+1100 (AEDT)"


However functions like
toISOString()
output in UTC, and although I can pull out individual components locally, I don't really want to fiddle around with padding and such. So I try this using moment.js:

moment().local().format(); // "2016-11-12T22:34:05+11:00"


Cool! Now I just need to adjust the format to a tiny bit:

moment().local().format('YYYY-MM-DThh:mm'); // "2016-11-12T10:39"


Waaaaaaait. Now it's in UTC again, even though I specified local.

In this particular case I could use string manipulation to just drop the end off for the date-time picker, but surely I'm going to reach a point where I want to output the local time in an arbitrary format. Am I missing something here?

Answer

Your second example isn't UTC, it's just using 12h format.

hh = 12h, HH = 24h. Try this instead:

moment().local().format('YYYY-MM-DTHH:mm')