Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to implement momentjs to display localtime

Before asking this question I have searched all stackoverflow and read the docs but I can't just understand how to convert one UTC date to local time of an user and display it in his format. I keep trying different methods but I keep getting the same time again and again.

so my django returns obj.created_on in UTC as - 2013-12-26T13:52:24 - no timezone Info here but I know its UTC

Now I want momentjs to auto detect the user's timezone and convert it in that timezone.

Can I have proper syntax for the same?

I was trying this as well:

new_date = moment(obj.created_on).utc().local().format()
like image 788
Keshav Agrawal Avatar asked Jan 14 '14 08:01

Keshav Agrawal


People also ask

Is Momentjs being deprecated?

js . This library helps you manipulate, validate, and accurately display the date and time according to… In fact moment. js is deprecated, the development team recommends to use date-fns instead.

What can I use instead of Momentjs?

And today, the most popular alternative to Moment. js is Day. js which surpassed date-fns on GitHub by stars (46,2k Day. js stars vs 37,7k date-fns stars).

How do you display timezone in moments?

To use moment-timezone, you will need [email protected]+ , moment-timezone. js , and the moment-timezone data. For convenience, there are builds available on momentjs.com/timezone/ with all the zone data or a subset of the data.

How do you convert UTC to local time zone?

utc(date). toDate(); localTime = moment(localTime). format('YYYY-MM-DD HH:mm:ss'); console. log("moment: " + localTime);


2 Answers

Moment has two different utc functions:

  • One is on a moment instance, used to switch the mode to UTC.

    moment(input).utc()
    
  • The other is on the moment prototype, used to interpret the input as already in UTC.

    moment.utc(input)
    

So, you want this syntax:

moment.utc(obj.created_on).local().format()
like image 69
Matt Johnson-Pint Avatar answered Nov 08 '22 15:11

Matt Johnson-Pint


moment($('#start').val()).utc().format("ddd, DD MMMM YYYY H:mm:ss");
moment($('#end').val()).utc().format("ddd, DD MMMM YYYY H:mm:ss");

will display Date format in UTC if you want the date in local format.

moment($('#start').val()).utc().local().format("ddd, DD MMMM YYYY H:mm:ss");
moment($('#end').val()).utc().local().format("ddd, DD MMMM YYYY H:mm:ss");

Default will take as GMT time. We need to convert that into our local format.

like image 29
Hari Prasad Avatar answered Nov 08 '22 14:11

Hari Prasad