Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date to localeString with milliseconds?

In Javascript I'm trying to convert a Date object to a locale string, with the toLocaleString() function. What I want is the converted locale string with milliseconds. Is that possible?

const time = "2018-12-03T16:24:05.150Z";
const date = new Date(time);
const str = date.toLocaleString();

console.log(date.toLocaleString()); //3-12-2018 17:24:05
like image 979
PsykoSoldi3r Avatar asked Dec 03 '18 16:12

PsykoSoldi3r


1 Answers

the key is fractionalSecondDigits

let iso_str = '2022-06-11T01:51:59.618Z';
let d = new Date(iso_str);

let tz = 'America/Santiago'
let options = {
    timeZone:tz ,
    timeZoneName:'longOffset',
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric',
    fractionalSecondDigits: 3
}


str_locale = d.toLocaleString("sv-SE",options);
//output: 2022-06-10 21:51:59,618 GMT−04:00
iso_str_tz = str_locale.replace(/(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2}),(\d+)\s+/,'$1-$2-$3T$4:$5:$6.$7').replace('GMT−', '-' ).replace('GMT+','+')
//output: 2022-06-10T21:51:59.618-04:00


console.log('iso_str               : ',iso_str);
console.log('str_locale            : ',str_locale);
console.log('iso_str_tz            : ',iso_str_tz);
console.log('iso_str_tz --> date   : ',new Date(iso_str_tz));
console.log('iso_str_tz --> iso_str: ',new Date(iso_str_tz).toISOString());
like image 99
Adán Escobar Avatar answered Sep 22 '22 20:09

Adán Escobar