0

I have a GMT date and time format coming from my dynamodb which I'm trying to convert to EST format using momentjs.

2019-06-27 20:00:43.156257

As soon as I drop the date into moment, it's converting it to +4 hours (when its supposed to be -4).

2019-06-28T00:00:43.156Z

All I'm doing is this.

const dbdate = [value-from-db]
const momentdate = moment(dbdate);

My output looks like:

dbdate: 2019-06-27 20:00:43.156257
momentdate: 2019-06-28T00:00:43.156Z

Fraction
  • 11,668
  • 5
  • 28
  • 48
Mike
  • 419
  • 1
  • 5
  • 14
  • 1
    From the [docs](https://momentjs.com/docs/#/parsing/): _"**Please read**: moment(...) is local mode. Ambiguous input (without offset) is assumed to be local time. Unambiguous input (with offset) is adjusted to local time."_ – Andreas Jun 28 '19 at 14:37

2 Answers2

1

You must use moment.utc() instead of moment():

const dbdate = '2019-06-27 20:00:43.156257';
const momentdate = moment(dbdate);
const utcmomentdate = moment.utc(dbdate);


console.log('local: \n', momentdate);
console.log('utc: \n', utcmomentdate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Fraction
  • 11,668
  • 5
  • 28
  • 48
1

There are two issues here:

1) Moment is performing timezone conversion using your local timezone - use moment.utc instead

2) Your date is not in a format that moment "officially" supports - although actually it's relaxed enough to parse your string. Ideally, it should be provided in proper ISO 8601 format to avoid any compatibility issues.

You could try something like:

 const dbdate = '2019-06-27 20:00:43.156257'.split(' ');
 const momentdate = moment.utc(dbdate[0] + 'T' + dbdate[1] + 'Z');
 alert(momentdate);

Here's a fiddle.

Hope this helps!

Tom Mettam
  • 2,903
  • 1
  • 27
  • 38