skip to Main Content

I have a MongoDB collection which contains some data created by users. I want to get exact time from createdAt filed. Please see the below image.

mongoDB screenshot

See the createdAt timestamp for a data created on 2023-08-17 22:30:02.

I’m building a next.js app. I’m able to split date from the timestamp using slice() method. But time given here is in some another format. Can anyone help me to get the time in standard format?

2

Answers


  1. There are some library exist that format you date and time and also make them separate.

    1. Dayjs : Link
    2. Moment : Link
    3. Luxon : Link
    4. date-fns : Link

    But you can achieve same thing with JavaScript as well.

    `${new Date('2023-08-17 22:30:02').getHours()}
     :${new Date('2023-08-17 22:30:02').getMinutes()}
     :${new Date('2023-08-17 22:30:02').getSeconds()}`
    
    Login or Signup to reply.
  2. I would suggest you handle the date formatting at server side to avoid potential inconsistent parsing of timezone between client side and server side using $dateToString.

    db.collection.aggregate([
      {
        "$set": {
          "createdAtString": {
            "$dateToString": {
              "date": "$createdAt",
              "format": "%Y-%M-%d %H:%m:%S",
              "timezone": "Asia/Calcutta"
            }
          }
        }
      }
    ])
    

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search