2

When i insert date time in mongodb, It's in UTC format

ISODate("2016-03-29T07:53:02.847Z")

When i fetch this result, it's in IST

Tue Mar 29 2016 13:23:02 GMT+0530 (IST)

I want to convert it to EST and display (only date and time)

Tue Mar 29 2016 02:56:22 GMT-0400 (EDT)

Tue Mar 29 2016 02:56:22 ( final output )

I have tried node-time, moment js etc. Did a lot of research but no result. Any help/suggestions are appreciated.

Community
  • 1
  • 1
node_saini
  • 727
  • 1
  • 6
  • 22
  • 1
    You shouldn't. It's good practice to store in UTC. That way **every** timezone has a consistent view of the data. Timezones are a "client" issue, and not one for the database. – Blakes Seven Mar 29 '16 at 08:36
  • Related: ["How to do query with timezone settings in Mongodb"](http://stackoverflow.com/questions/14496489/how-to-do-query-with-timezone-settings-in-mongodb) and ["Aggregating in local timezone in mongodb"](http://stackoverflow.com/questions/31353740/aggregating-in-local-timezone-in-mongodb/) – Blakes Seven Mar 29 '16 at 08:42
  • You could store GMT offset in another field, to retain this information. Sqlserver has a data type for this exact purpose. Unfortunately mongo, and most other databases don't. – user1751825 Mar 29 '16 at 09:08
  • It doesn't save in local, it saves in UTC. You are probably confusing the output of something like `console.log(document)` which will "stringify" the date as a local value. Thats the `.toString()` method of a JavaScript `Date` object at work. You can do this in the shell as well `new Date().toString()` as opposed to `new Date()`, where one shows the "local string" and the other shows you that it's really a UTC date. – Blakes Seven Mar 29 '16 at 10:20
  • Sorry. I wrote it wrong. It saves in UTC but while fetching it converts UTC into IST. How ? Why ? Also You did not answer my second question in previous comment. @BlakesSeven – node_saini Mar 29 '16 at 10:24
  • I just told you. `.toString()`! Go and try it. It's still a UTC value, but just "stringified" that way. – Blakes Seven Mar 29 '16 at 10:33
  • If i console.log(result of my query) it will give me [{ _id: 60, updated_at: Tue Mar 29 2016 15:43:25 GMT+0530 (IST), created_at: Tue Mar 29 2016 15:43:25 GMT+0530 (IST) }] whereas in mongo shell it is { "_id" : 60, "updated_at" : ISODate("2016-03-29T10:13:25.718Z"), "created_at" : ISODate("2016-03-29T10:13:25.718Z") } – node_saini Mar 29 '16 at 10:48

1 Answers1

1

Moment.js works in node.js and has timezone support that can convert from UTC to any desired timezone: http://momentjs.com/timezone/

var moment = require('moment-timezone');
var jun = moment("2014-06-01T12:00:00Z");
jun.tz('America/New_York').format('ddd MMM DD YYYY HH:mm:ss');

You'll need to npm install moment timezone first

npm install moment-timezone --save
Paul Humphreys
  • 338
  • 2
  • 9