17

I am working with momentjs and converting dates to different time zones using convertedDate = moment().utcOffset(timezone).format(). This works well but it is a string and I need to transform it to date object.

I've tried new Date(convertedDate) and moment().utcOffset(timezone).toDate() but that returns my current timezone as a date object. How can I keep the converted timezone?

cocoa
  • 3,806
  • 7
  • 29
  • 56

3 Answers3

11

So I wasn't very far off. The format needs to exclude timezone for it to work. This code finally worked how I needed it to.

convertedDate = new Date(moment().utcOffset('-4').format('YYYY-MM-DD HH:mm'));

cocoa
  • 3,806
  • 7
  • 29
  • 56
  • 3
    This is not a good approach. It relies on the `Date` object's parsing, and it's basically lying about the input being four hours off from local time. The `Date` object *cannot* represent another time zone. – Matt Johnson-Pint Aug 29 '17 at 18:36
6

A cleaner approach to get a native Date object with time according to the timezone, using moment would be following:

convertedDate = moment.utc(moment.tz(timezone).format('YYYY-MM-DDTHH:mm:ss')).toDate()

PS: assuming two things

  • you have imported both 'moment' and 'moment-timezone'.
  • value of timezone is given like 'Asia/Kolkata' instead of an offset value
Ameen Ahsan
  • 61
  • 1
  • 3
2

This should work:

I have the same issue. Just get the Date as a string using the same approach that you are using. Let's say your date is, for example: '2018-08-05T10:00:00'.

Now you need the Date object with correct time. To convert String into object without messing around with timezones, Use getTimezoneOffset:

var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);

getTimezoneOffset() will return either negative or positive value. This must be subtracted to work in every location in the world.

saran3h
  • 12,353
  • 4
  • 42
  • 54