107

I use the Moment.js and Moment-Timezone frameworks, and have a Moment.js date object which is explicitly in UTC timezone. How can I convert that to the current timezone of the browser?

var testDateUtc = moment.tz("2015-01-30 10:00:00", "UTC");
var localDate = ???

So it would be fine if I could find out the users local time zone; or alternatively I'd like to convert the date object into another data object which just uses the "local timezone", no matter what that actually is.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
oliver
  • 6,204
  • 9
  • 46
  • 50

5 Answers5

176

You do not need to use moment-timezone for this. The main moment.js library has full functionality for working with UTC and the local time zone.

var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).local();

From there you can use any of the functions you might expect:

var s = localDate.format("YYYY-MM-DD HH:mm:ss");
var d = localDate.toDate();
// etc...

Note that by passing testDateUtc, which is a moment object, back into the moment() constructor, it creates a clone. Otherwise, when you called .local(), it would also change the testDateUtc value, instead of just the localDate value. Moments are mutable.

Also note that if your original input contains a time zone offset such as +00:00 or Z, then you can just parse it directly with moment. You don't need to use .utc or .local. For example:

var localDate = moment("2015-01-30T10:00:00Z");
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • 7
    You should be aware that this method doesn't take DST offsets into account, it's safer to use `moment-timezone` library – Jaime Agudo Aug 18 '15 at 17:14
  • 2
    @Jaime not true. `local` does indeed take DST into account. – Matt Johnson-Pint Aug 18 '15 at 23:38
  • 1
    You can check on your own for example translating from `EST` to `CET`, I'll put an example tomorrow if you want like `NY`->`Madrid`. I'll accept the counterexample :) – Jaime Agudo Aug 18 '15 at 23:41
  • 1
    you're correct that moment can't do that type of conversion without moment-time zone. However, it *can* properly convert between UTC and local, which is what the OP asked. – Matt Johnson-Pint Aug 18 '15 at 23:44
  • 3
    Local rules come from the browser. So as long as the local time zone includes DST, moment will use it. – Matt Johnson-Pint Aug 18 '15 at 23:46
  • Thing is local time zone takes DST into account but not the other TZs, hence the conversion is wrong. In my particular case it didn't work out for `NY`->`Madrid` on Chrome Canary so I just wanted to add my $0.2 – Jaime Agudo Aug 19 '15 at 10:23
  • 1
    You also can chain into single line, `moment.utc("2015-01-30 10:00:00").local().format()` – foxiris Aug 16 '21 at 07:49
35
var dateFormat = 'YYYY-DD-MM HH:mm:ss';
var testDateUtc = moment.utc('2015-01-30 10:00:00');
var localDate = testDateUtc.local();
console.log(localDate.format(dateFormat)); // 2015-30-01 02:00:00
  1. Define your date format.
  2. Create a moment object and set the UTC flag to true on the object.
  3. Create a localized moment object converted from the original moment object.
  4. Return a formatted string from the localized moment object.

See: http://momentjs.com/docs/#/manipulating/local/

Igbanam
  • 5,904
  • 5
  • 44
  • 68
AndrewHenderson
  • 4,686
  • 3
  • 26
  • 33
  • This answer would be even better if it explained why that works, perhaps with references to the documentation. Also, you may want to explain how this answer is different from the one posted in March... – Heretic Monkey Dec 10 '15 at 23:24
  • @AndrewHenderson, Time is one hour ahead of the local machine time.Why it happening? – Ramesh Papaganti Apr 10 '17 at 14:04
  • @RameshPapaganti Perhaps Daylight Savings? For example PDT vs PST. Moment has been known to change the API between versions especially when it comes to localization. Let me know if you found the cause. – AndrewHenderson Apr 21 '17 at 01:11
7

Here's what I did:

var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();

Where {{ time }} is the utc timestamp.

sayan
  • 1,520
  • 17
  • 33
5

Use utcOffset function.

var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).utcOffset(10 * 60); //set timezone offset in minutes
console.log(localDate.format()); //2015-01-30T20:00:00+10:00
Alexey Ryazhskikh
  • 2,458
  • 4
  • 32
  • 51
1

class Time extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      parentTime: '',
      localTime: '',
      parentTz: ''
    }
  }

  componentDidMount() {
    const inputTz = "America/Toronto"
    const originTime = "2013-11-18 11:55"
    const time = moment.tz(originTime, inputTz)
    const localtz = moment.tz.guess()
    const date = time.clone().tz(localtz)
    const formatDate = moment(date).format('MMMM Do YYYY, h:mm:ss A z')
     console.log(formatDate, localtz)
    this.setState({parentTime: originTime, localTime: formatDate, parentTz: inputTz })
  }


  render() {
  const {parentTime, parentTz, localTime} = this.state
    return (
      <div>
      <p>{parentTime}<br/> in {parentTz}<br/> to {localTime}</p>
      </div>
    )
  }
}


ReactDOM.render(
  <Time />,
  document.getElementById('time')
);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-1970-2030.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.3.0/react-dom.min.js"></script>
<div id="time"></div>

the best way to get a user's time zone is using moment-timezone

import moment from 'moment-timezone'

// using utc time here
const time = moment.tz("2021-04-14T02:08:10.370Z")
const localtz = moment.tz.guess()
const date = time.clone().tz(localtz)
const formatDate = moment(date).format('MMMM Do YYYY, h:mm:ss A z')
console.log(formatDate)

this way you will be able to convert your time into a local timezone specific time

Nishith
  • 928
  • 9
  • 13