Search code examples
node.jstimestampdayjs

How do i save timestamps in 6 digit numbers using daysjs?


I have the following date being saved in the DB (postgres) from a ruby application.

2021-11-04 07:21:15.494678

Now i have a node app that i need to save the date format in exactly the same format. I have almost got it right with the below function :-

const generateCurrentDateString = () => {
  /* 
    Refer https://day.js.org/docs/en/display/format
    For format and advanced format
  */
  return dayjs().format('YYYY-MM-DD HH:mm:ss.X')
}

I output i get is

2021-11-04 12:57:04.1636010824

As you can notice the last part is 1636010824 which is ofcourse constructed using X, which is actually a timestamp in secounds. But what exactly is 494678 ? and how can i create this using dayjs ? i am unable to find any options that output a 6 digit no. ?

P.S. Days.js format docs can be found HERE.


Solution

  • The 494678 after dot is microseconds:

    Time.now.utc.iso8601(6) # ruby
    

    Library "day.js" does not work with microseconds.

    So if microseconds are not important to you, but you need to keep the recording format, a possible solution is to only use milliseconds (3 digits) and fill the remaining positions with three zeros:

    dayjs().format('YYYY-MM-DD HH:mm:ss.SSS000')
    

    Or if you know the value in microseconds, then just concatenate:

    dayjs().format('YYYY-MM-DD HH:mm:ss.') + microseconds
    

    Here is the respective docs page where you could find mode examples as well as the list of formatting tokens.