1

Hi im using moment js to convert this string 20:00 I tried:

var a = moment("20:00", "HH:mm")
console.log(a.format()) // 2016-09-08T20:00:00+01:00

the problem when I store in mongodb it become

2016-09-10T19:00:00.000Z

I want to store 2016-09-10T20:00:00.000Z

anyway can explain why please ?

Doe
  • 11
  • 2

2 Answers2

1

When you say that you want to store 2016-09-10T20:00:00.000Z what you are saying is that you want to assume that your date and time is UTC.

To assume that the date you are parsing is a UTC value, use moment.utc

var a = moment.utc("20:00", "HH:mm")
console.log(a.format()) // 2016-09-08T20:00:00Z

Note that when you parse a time without a date, moment assumes the current date. This may not be the behavior that you want.

I'm also not sure if you want a UTC date (which is what you are saying), or a local date without an offset indicator. If you want a local date without an offset indicator, simply use a format without an offset:

moment.utc("20:00", "HH:mm").format('YYYY-MM-DDTHH:mm:ss.SSS')
"2016-09-08T20:00:00.000"

If you are dealing with local dates that do not have a time zone association, I recommend using moment.utc to parse, as this will ensure that the time does not get shifted to account for DST in the current time zone.

For more information about how to parse dates into the time zone or offset that you would like in moment, see my blog post on the subject.

Maggie Pint
  • 2,432
  • 1
  • 11
  • 15
0

This it how it should look:

var a = moment("20:00", "HH:mm")
console.log(a.utcOffset('+0000').format())
<script src="http://momentjs.com/downloads/moment.min.js"></script>

Doe, the problem is that you are using timezones when you create the date.

MomentJS uses your current timezone automatically.

Mongo however saves the time as it would be in another timezone.

Therefore, if you want the two strings to format the same way, you need to set the timezone.

Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
  • Please check my edit. As you've got the right answer, but you forgot the OP wants `20:00` in UTC, not `20:00+01:00` which is `19:00` UTC. – evolutionxbox Sep 08 '16 at 15:26