240

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,701
  • 3
  • 17
  • 17

11 Answers11

363

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
  • 118,978
  • 58
  • 307
  • 400
axon
  • 4,081
  • 1
  • 12
  • 14
  • 25
    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
  • 2
    @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
110

Try this:

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

var local_date= moment.utc(utcTime).local().format('YYYY-MM-DD HH:mm:ss');
Eugene Barsky
  • 5,780
  • 3
  • 17
  • 40
JAMZAD
  • 1,101
  • 1
  • 7
  • 5
32
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
  • 520
  • 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
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>
Brady Huang
  • 1,852
  • 20
  • 23
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');
  },
Fung
  • 961
  • 1
  • 8
  • 17
5

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,221
  • 20
  • 26
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
  • 7,172
  • 5
  • 55
  • 69
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()
Sokushinbutsu
  • 83
  • 1
  • 5
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
  • 30,962
  • 25
  • 85
  • 135
MING WU
  • 2,962
  • 1
  • 12
  • 16
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
  • 3,365
  • 26
  • 26
0

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

faheem999
  • 52
  • 3