Here's how I do it:
function date_to_string_with_milliseconds(date){
let date_str = date.toString()
let date_without_milliseconds = new Date(date_str) // truncated date since milliseconds are not included
let milliseconds_delta = date - date_without_milliseconds
let date_str_with_milliseconds = date_str.replace(/(^.*:\d\d:\d\d)(.*$)/, `$1:${milliseconds_delta}$2`)
return date_str_with_milliseconds
}
Usage:
date_to_string_with_milliseconds(new Date(Date.now())).toString()
// outputs 'Wed Nov 30 2022 16:40:42:991 GMT+0530 (India Standard Time)'
Doing it this way has a couple of advantages:
The date string that you get as output can be converted back to a
Date object.
This doesn't change the original date object in any
way since you only need a string representation.