36

In Mongodb I am storing date and time in ISODate format.

Which looks like this

ISODate("2012-07-14T01:00:00+01:00")

Using nodejs/javascript, how can I display the time component so I would get something like this

Time : 01:00

I am using momentjs to make this easier but from what I can tell momentjs does seem to support the ISODate format.

Thanks for you help.

jamjam
  • 3,171
  • 7
  • 34
  • 39

4 Answers4

38

JavaScript's Date object supports the ISO date format, so as long as you have access to the date string, you can do something like this:

> foo = new Date("2012-07-14T01:00:00+01:00")
Sat, 14 Jul 2012 00:00:00 GMT
> foo.toTimeString()
'17:00:00 GMT-0700 (MST)'

If you want the time string without the seconds and the time zone then you can call the getHours() and getMinutes() methods on the Date object and format the time yourself.

Sarah Roberts
  • 830
  • 7
  • 13
  • I used momentjs to do the formatting but had to pass getFullYear, getMonth, getDate, getHours and getMinutes by first extracting it from date object as you said. – jamjam Jul 15 '12 at 18:26
  • Don't parse strings with the Date constructor, it is very inconsistent across implementations. While ISO formats are specified in ES5, not all browsers in use support it, and there are inconsistencies in how they are treated. E.g. "2012-07-14T01:00:00+01:00" should be parsed as a local string (i.e. using system time zone settings), but ""2012-07-14" should be parsed as UTC. – RobG Feb 09 '16 at 21:11
33

MongoDB's ISODate() is just a helper function that wraps a JavaScript date object and makes it easier to work with ISO date strings.

You can still use all of the same methods as working with a normal JS Date, such as:

ISODate("2012-07-14T01:00:00+01:00").toLocaleTimeString()

// Note that getHours() and getMinutes() do not include leading 0s for single digit #s
ISODate("2012-07-14T01:00:00+01:00").getHours()
ISODate("2012-07-14T01:00:00+01:00").getMinutes()
Stennie
  • 63,885
  • 14
  • 149
  • 175
2

you can use mongo query like this

yearMonthDayhms: { $dateToString: { format: "%Y-%m-%d-%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

HourMinute: { $dateToString: { format: "%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

enter image description here

Chris Moutray
  • 18,029
  • 7
  • 45
  • 66
Jin Thakur
  • 2,711
  • 18
  • 15
1
// from MongoDate object to Javascript Date object

var MongoDate = {sec: 1493016016, usec: 650000};
var dt = new Date("1970-01-01T00:00:00+00:00");
    dt.setSeconds(MongoDate.sec);
user3684669
  • 117
  • 1
  • 3