207

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?

brian Scroggins
  • 2,351
  • 3
  • 16
  • 17

10 Answers10

325

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>
vsync
  • 103,437
  • 51
  • 275
  • 359
axon
  • 3,701
  • 1
  • 11
  • 13
  • 23
    didn't work for me, the time is still 5 hours ahead of my browers time which is correct – brian Scroggins Sep 12 '15 at 23:39
  • if momentjs is aware of the local timezone, is there a way to retrieve it or is moment.tz.guess() needed to do this? – jEremyB Jul 12 '19 at 16:58
  • @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 case – axon Jul 15 '19 at 05:05
  • 1
    @brianScroggins, be sure to not forget `.utc(date)`. In first part, the line `var local = ...` not having it can be misleading. – Jocelyn Jan 09 '20 at 13:09
  • I used moment in nodeJs environment and I had to set the timezone in environment-vars for proper work: TZ='Europe/Vienna' https://stackoverflow.com/a/9849524/2560683 – dduft Apr 30 '21 at 19:17
94

Try this:

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

var local_date= moment.utc(utcTime ).local().format('YYYY-MM-DD HH:mm:ss');
Beat
  • 4,330
  • 2
  • 31
  • 49
JAMZAD
  • 941
  • 6
  • 5
  • 5
    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. – Juan Pablo Ugas Nov 19 '18 at 00:10
  • 5
    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. – Alex Ehlert Jan 14 '20 at 18:37
27
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

Abdur Rahim
  • 460
  • 8
  • 18
  • 4
    This works great but why doesn't .local() return the same result? – Steve Jun 11 '19 at 10:11
  • 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) – Steve Jun 12 '19 at 15:18
18

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>
Brady Huang
  • 1,473
  • 16
  • 22
5

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');
  },
Fung LAM
  • 913
  • 1
  • 8
  • 17
4

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');
WoodyDRN
  • 1,161
  • 20
  • 25
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

CodingYourLife
  • 5,662
  • 5
  • 46
  • 65
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');
Dharman
  • 26,923
  • 21
  • 73
  • 125
MING WU
  • 2,652
  • 1
  • 11
  • 15
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"
Rohit Parte
  • 2,635
  • 22
  • 21
1

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()
Sokushinbutsu
  • 73
  • 1
  • 5