1

I want to get the current date including the milliseconds. I know that Date.now() is returning the Unix epoch time in milliseconds, but the object Date contains only the Date and timestamp with second precision.

console.log("Time: " + new Date);

Time: Tue Apr 14 2020 12:21:26 GMT+0200 (Central European Summer Time)

But I want it to look like this:

Time: Tue Apr 14 2020 12:21:26.500 GMT+0200 (Central European Summer Time)

Is there a way to change the format in order to display the milliseconds as well or do I need to concatenate the Date string with new Date().getMilliseconds();?

Anurag Srivastava
  • 12,230
  • 3
  • 21
  • 36
Georgi Stoyanov
  • 490
  • 6
  • 19
  • as far as I can see this is parsing a time format including milliseconds into JS timestamp, what I want is the other way around, to get the current timestamp and visualize it with millisecond precision. – Georgi Stoyanov Apr 14 '20 at 10:50

1 Answers1

1

You can use moment.js to achieve the format you need, and the other option is to concatenate manually

console.log(moment().format('YYYY-MM-DD HH:mm:ss.SSS'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment-with-locales.min.js"></script>
Anurag Srivastava
  • 12,230
  • 3
  • 21
  • 36
  • 1
    If you are just formatting dates, there are very much smaller libraries than moment.js, e.g. [fecah.js](https://github.com/taylorhakes/fecha) (not a recommendation, just an example). – RobG Apr 14 '20 at 11:09