Bowis
Bowis

Reputation: 632

MomentJS keeps defaulting date to GMT

I have

moment(line.dateRange[0], 'DD-MM-YY HH:mm').toDate()

set up, where the input is a string: 15-10-2021 09:00

Moment keeps outputting: 2020-10-15T07:00:00.000Z, even though my process.env.TZ of my nodeJS server is Europe/Amsterdam.

for (const line of orderLines) {
      
    let orderLine = {
            bookingID: bookingDB.id,
            bookingStart: moment(line.dateRange[0], 'DD-MM-YY HH:mm').format(),
            bookingEnd: moment(line.dateRange[1], 'DD-MM-YY HH:mm').format(),
            productID: line.productID,
            type: line.type
         }
         console.log(orderLine)
         lines.push(orderLine);
      }
      const orderLinesDB = await BookingLine.bulkCreate(lines);
      console.log(orderLinesDB)
      res.status(200).send(orderLinesDB);

Upvotes: 1

Views: 45

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30685

I suspect you're seeing the output 2020-10-15T07:00:00.000Z because you're doing:

console.log(moment('15-10-2021 09:00', 'DD-MM-YY HH:mm').toDate())

What you're seeing in the output is UTC time, which will be 2 hours behind Europe/Amsterdam, since Node.js calls toISOString() when logging dates.

Try calling moment.format() to see local time, or use .toDate().toLocaleString() or .toDate().toString().

For example:

const input = '15-10-2021 09:00';

console.log('UTC time:', moment(input, 'DD-MM-YY HH:mm').toDate())
console.log('Local time:', moment(input, 'DD-MM-YY HH:mm').format())
console.log('Local time (II):', moment(input, 'DD-MM-YY HH:mm').toDate().toLocaleString())
console.log('Local time (III):', moment(input, 'DD-MM-YY HH:mm').toDate().toString())

Should output

 UTC time: 2020-10-15T07:00:00.000Z
 Local time: 2020-10-15T09:00:00+02:00
 Local time (II): 15/10/2020, 09:00:00
 Local time (III): Thu Oct 15 2020 09:00:00 GMT+0200 (Central European Summer Time)

Which is what we would expect.

Upvotes: 3

Related Questions