Moment Js UTC to Local Time
Asked Answered
B

11

247

I'm trying to convert UTC time to the local time. I've been following this example from this link: http://jsfiddle.net/FLhpq/4/light/. I can't seem to get the right local output. For example, if its 10: 30 am in here, instead of getting 10:30 ill get 15: 30. Here is my code:

var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');

var localTime  = moment.utc(date).toDate();

localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');

console.log("moment: " + localTime);

No matter what I do the time always comes out at UTC time. I live in Houston so I know timezone is the issue. I've followed the code in the link but can seem to get the local time. What am I doing wrong?

Burgener answered 12/9, 2015 at 15:43 Comment(0)
M
374

To convert UTC time to Local you have to use moment.local().

For more info see docs

Example:

var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');

console.log(date); // 2015-09-13 03:39:27

var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');

console.log(local); // 2015-09-13 09:39:27

Demo:

var date = moment.utc().format();
console.log(date, "- now in UTC"); 

var local = moment.utc(date).local().format();
console.log(local, "- UTC now to local"); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Meticulous answered 12/9, 2015 at 16:0 Comment(5)
didn't work for me, the time is still 5 hours ahead of my browers time which is correctBurgener
if momentjs is aware of the local timezone, is there a way to retrieve it or is moment.tz.guess() needed to do this?Krems
@jEremyB, moment().format('Z') and moment().format('ZZ') can help you. Also, take a look at (new Date()).getTimezoneOffset() maybe it's enough for you caseMeticulous
@brianScroggins, be sure to not forget .utc(date). In first part, the line var local = ... not having it can be misleading.Hasty
I used moment in nodeJs environment and I had to set the timezone in environment-vars for proper work: TZ='Europe/Vienna' https://mcmap.net/q/108554/-how-can-i-set-the-default-timezone-in-node-jsDumbarton
P
113

Try this:

let utcTime = "2017-02-02 08:00:13";

var local_date= moment.utc(utcTime).local().format('YYYY-MM-DD HH:mm:ss');
Percyperdido answered 14/12, 2017 at 6:49 Comment(3)
Specifying the zone in which it was saved worked for me (this answer). Also, found it makes life easier if you always save things in utc then format on the client side.Parley
This worked in my case where we are saving the time in UTC in our db and only displaying local time on the client. Thanks.Banwell
This answer worked for me. Converting into local time only in the client side.Gregson
C
33
let utcTime = "2017-02-02 08:00:13.567";
var offset = moment().utcOffset();
var localText = moment.utc(utcTime).utcOffset(offset).format("L LT");

Try this JsFiddle

Comyns answered 3/2, 2017 at 19:15 Comment(2)
This works great but why doesn't .local() return the same result?Lutz
this fiddle returns the following result on my computer: 02/02/2017 8:00 AM (UTC Time) 02/02/2017 10:00 AM (Local Time) 02/02/2017 9:00 AM (Local Time another way)Lutz
T
21

To convert UTC to local time

let UTC = moment.utc()
let local = moment(UTC).local()

Or you want directly get the local time

let local = moment()

var UTC = moment.utc()
console.log(UTC.format()); // UTC time

var cLocal = UTC.local()
console.log(cLocal.format()); // Convert UTC time

var local = moment();
console.log(local.format()); // Local time
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Turpin answered 5/2, 2020 at 3:3 Comment(0)
S
6

Note: please update the date format accordingly.

Format Date

   __formatDate: function(myDate){
      var ts = moment.utc(myDate);
      return ts.local().format('D-MMM-Y');
   }

Format Time

  __formatTime: function(myDate){
      var ts = moment.utc(myDate);
      return ts.local().format('HH:mm');
  },
Signory answered 10/5, 2017 at 1:57 Comment(0)
E
6

This is old question I see, but I didn't really get what I was looking for. I had a UTC datetime which was formatted without timezone. So I had to do this:

let utcDatetime = '2021-05-31 10:20:00';
let localDatetime = moment(utcDatetime + '+00:00').local().format('YYYY-MM-DD HH:mm:ss');
Emmanuelemmeline answered 31/5, 2021 at 8:23 Comment(1)
You're a godsend today, this is the part I was missing!Importunate
B
3

I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!

Full Example on Codesandbox (DEMO):

https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js

Battlefield answered 7/10, 2020 at 4:25 Comment(0)
S
2

This is what worked for me, it required moment-tz as well as moment though.

const guess = moment.utc(date).tz(moment.tz.guess());
const correctTimezone = guess.format()
Spiel answered 14/8, 2020 at 19:33 Comment(0)
D
2

Here is what I do using Intl api:

let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney

this will return a time zone name. Pass this parameter to the following function to get the time

let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});

let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});

you can also format the time with moment like this:

moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');
Dolmen answered 15/1, 2021 at 21:36 Comment(0)
G
1

I've created one function which converts all the timezones into local time.

Requirements:

1. npm i moment-timezone

function utcToLocal(utcdateTime, tz) {
    var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
    var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
    var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
    var localDateTime
    var hours = zoneValue.split(":")[0]
    var minutes = zoneValue.split(":")[1]
    if (operator === "-") {
        localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
    } else if (operator) {
        localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
    } else {
        localDateTime = "Invalid Timezone Operator"
    }
    return localDateTime
}

utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")

//Returns "2019-11-14 12:45:37"
Groats answered 14/11, 2019 at 7:32 Comment(1)
this worked for me! thank you! I used utcToLocal("2019-11-14 07:15:37", moment.tz.guess())Akvavit
H
1

In DataTables or Grids in react, we can use below.

MomentJS.utc(row?.registrationTime).local().format('lll')

In Db: Database Image

In Grid: Grid Image

Huddleston answered 2/3, 2023 at 6:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.