Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js, how to just change a format of a date without changing timezone?

I want to change a format of a date and time string. But moment.js changes timezone to my system timezone (+3):

// This is a string:
"2013-09-20 23:59:59 +0100"

// I want to change it to this:
"20-09-2013 23:59:59 +0100"

// This is what I do and what I get. 1 hour is added by force:
moment("2013-09-20 23:59:59 +0100").format("DD-MM-YYYY HH:mm:ss ZZ")
"21-09-2013 01:59:59 +0300"

How to just change a format without changing timezone?

like image 422
Green Avatar asked Sep 06 '13 11:09

Green


People also ask

How do I change a moment date to a specific format?

Date Formatting Date format conversion with Moment is simple, as shown in the following example. moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format.

Does moment change timezone?

By default, moment objects are created in the local time zone. Local time zone - it's a time zone which is set in a browser or on your node. js server. To change the default time zone, use moment.

Why you shouldnt use moment JS?

However, Moment. js has too many drawbacks compared to modern date and time libraries. Its API is not immutable, it is large and it doesn't support tree shaking. Even the Moment team discourages to use their library in new projects.


1 Answers

See moment issue #887, directly regarding this. It may be easier in a future version, but the current workaround is as follows:

var input = "2013-09-20 23:59:59 +0100";
var m = moment(input).zone(input);
m.format("DD-MM-YYYY HH:mm:ss ZZ")
like image 67
Matt Johnson-Pint Avatar answered Nov 14 '22 23:11

Matt Johnson-Pint