Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to display timestamp in unix format to ISODate?

We stored a date using unix timestamp in MongoDB, how do I get the date when I do the query? Is there a way to display timestamp in ISODate format?

like image 359
Adam Lee Avatar asked Feb 23 '13 15:02

Adam Lee


People also ask

What format is Unix timestamp?

Unix epoch timestamps are supported in the following formats: 10 digit epoch time format surrounded by brackets (or followed by a comma). The digits must be at the very start of the message. For example, [1234567890] or [1234567890, other] followed by the rest of the message.

Is Unix timestamp an integer?

The Unix timestamp is a single signed integer that grows by one every second, allowing computers to store and manipulate conventional date systems. The software is then translated into a human-readable format. The Unix timestamp is the number of seconds calculated since January 1, 1970.


1 Answers

Background

  • A unixtime value represents seconds since the epoch (Jan 1, 1970).

  • A JavaScript Date() represents milliseconds since the epoch.

  • In MongoDB, ISODate() is a convenience wrapper for Date() that allows you to create dates from ISO strings in the mongo shell. If you use new Date() in the shell, it will return an ISODate().

Conversion

To convert between a unixtime and an ISODate() you can multiply your unix timestamps by 1000 and pass this value to the new Date() constructor.

A simple example in the mongo shell:

> db.mydata.insert({
    unixtime: 1362143511
})

> var doc = db.mydata.findOne();

// convert unixtime seconds to milliseconds and create JS date
> var date = new Date(doc.unixtime * 1000);

> date
ISODate("2013-03-01T13:11:51Z")
like image 85
Stennie Avatar answered Sep 20 '22 08:09

Stennie