How to use and format the TIMESTAMP in javascript?

I’m trying to work with the TIMESTAMP… I’m posting here because I can’t find ANY documentation or examples online or this site. If anybody knows any documentation that would be great!

I’m using MongoDB is a basic CMS, for like blog posts. I’m saving created and edited TIMESTAMPS for each post. I have some mongoDB web hook functions that expose these posts to an API, making a headless CMS. The CMS works great, but those timestamps look like:

  "created": {
    "$timestamp": {
      "t": 1631414145,
      "i": 5
    }
  },
  "edited": {
    "$timestamp": {
      "t": 1631414145,
      "i": 6
    }
  },

Questions:

I want to both display these in useful way in the blog post headers and order by them. What is the best way to format this? How do I do it? I think I’d prefer formatting api side, but I’m open to whatever.

I know the ObjectId contains the created date somehow, is it more standard to use that somehow?

I have triggers that format the blog posts… how do I automatically stamp the edited?

I’m not super opinionated on this, what’s the easiest standard way to work with and format TIMESTAMPs with mongodb?

Thanks for any help!

General question: I always find MongoDB documentation and community very frustrating. Just trying to do basic thing, like format a timestamp, on other platforms I can find examples and documentation in seconds. Why is it so difficult with MongoDB? What am I doing wrong?

Is there a Discord for MongoDB?

I suggest save the created and edited time fields as Date data type (instead of Timestamp type).

For example,

var createdDt = new Date()
db.posts.insertOne({ title: "Working with dates", created: createdDt })
db.posts.findOne()
// returns
{
        "_id" : ObjectId("619474dd9043453a52147dd7"),
        "title" : "Working with dates",
        "created" : ISODate("2021-11-17T03:19:56.186Z")
}

Thanks!

Date() itself serialized as a similar useless object to TIMESTAMP. But storing this post.edited = new Date().toJSON(); creates that more meaningful iso date strong… with presumably I can work with on the frontend.

I think this approach will work for me for now… is this standard?

I think it is not. MongoDB data allows storing date as a date type. It is efficient storage, can be converted to any other forms (e.g., to string), has all the date/time related information, can be used for searching and sorting (compare with other dates), extract and use the different date fields (day, month, year, hour, min, sec, etc.) from it, perform date arithmetic, etc. All these operations can be applied using various query or aggregation operators (see Date Expression Operators).

1 Like

I might be too late for this but to convert mongodb timestamp to js date what I did is

const document = {
"_id": 'doc_id',
"created": {
    "$timestamp": {
      "t": 1631414145,
      "i": 5
    }
  },
}
console.log(new Date(document?.created?.$timestamp.t * 1000))