Carlos Salazar
Carlos Salazar

Reputation: 1898

Moment return the same value passed to it instead of utc value

Im trying to trasform a date to utc but moment return the same value i use.

for example

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

if i use date = '2022-01-07 11:30:00' moment return 2022-01-07 11:30:00

do i have to set the timezone of the value first? why moment return the wrong value? it should return +3 hours that date.

Upvotes: 1

Views: 415

Answers (3)

0stone0
0stone0

Reputation: 43934

You'll need to define the timezone in which the date is, then the offset will be as expected:

Example, using Europe/Amsterdam as timezone

const date = '2022-01-07 11:30:00';

const utc = moment(date, 'YYYY-MM-DD HH:mm:ss')
              .tz('Europe/Amsterdam')
              .utc()
              .format('YYYY-MM-DD HH:mm:ss');
console.log(utc);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.32/moment-timezone-with-data.min.js"></script>

This will output 2022-01-07 10:30:00 since Amsterdam time is -1 compared to UTC.


Small side node, quoting MomentJS Project Status page

We now generally consider Moment to be a legacy project in maintenance mode. It is not dead, but it is indeed done.

In practice, this means:

  • We will not be adding new features or capabilities.
  • We will not be changing Moment's API to be immutable.
  • We will not be addressing tree shaking or bundle size issues.
  • We will not be making any major changes (no version 3).
  • We may choose to not fix bugs or behavioral quirks, especially if they are long-standing known issues.

Upvotes: 1

Rodrigo Klosowski
Rodrigo Klosowski

Reputation: 406

This returns the same date since you never indicated any timezone

var time = moment("2013-08-26 16:55:00") //this creates time in my tz

You can set a timezone like this:

var time = moment("2013-08-26 16:55:00").tz("America/Los_Angeles");

Upvotes: 0

Dave
Dave

Reputation: 7717

The data you pass in doesn't have any indication of the timezone it's in, so moment is (I believe) assuming it's in utc already.

In related news, look into using the date-fns library instead of moment. Moment is getting old...

Moment github

Moment.js is a legacy project, now in maintenance mode. In most cases, you should choose a different library.

Upvotes: 0

Related Questions