Toran Billups
Toran Billups

Reputation: 27399

Why does moment format in a different timezone?

I have a day string that looks like this "2013-10-29"

I then have a time string that looks like this "9:00"

If I use moment to format these and generate a date, I keep getting 12 as the time for some reason

new Date(moment(day + " " + start).format('YYYY-MM-DD h:m'));

Tue Oct 29 2013 12:00:00 GMT-0500 (CDT)

How can I use moment to get the local time correctly?

Upvotes: 1

Views: 460

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241475

I think what you are looking for is:

moment(day + " " + start, 'YYYY-MM-DD H:mm').toDate()

If you need to specify an input format, that goes as a parameter to the moment constructor. If you use the format method, that is the output format to create a string.

But Adriano makes some very good points also. You shouldn't use a Date object unless you are passing it to some other code or control that requires it. End users always need a string for display.

As to why your code didn't pick up the time properly, consider that when you used h:m that would format as 9:0. Some browsers might not understand that as a valid time. You should have H:mm to get 9:00. (The Date constructor's parsing is implementation specific.) I also used a capital H for 24 hour clock. If you want to stick to a 12 hour clock, then you should also include an am/pm designator with the format h:mm a.

Upvotes: 1

Adriano Repetti
Adriano Repetti

Reputation: 67080

You display a Date object and then it's representation depends on the browser. What you're doing is:

  1. Creating a Date object with moment();
  2. Formatting that Date with format(), now you have string you want.
  3. Parsing it back to a Date;
  4. Converting that date back to string with default Date.toString() browser dependant implementation.

This string is what you have and what you need too:

moment(day + " " + start).format('YYYY-MM-DD h:m')

Do not parse it back to a Date object (it may even fail, you're using the constructor with dateString parameter: see MDN), Date.toString() will always produce the format preferred by browser.

Upvotes: 3

Related Questions