PsykoSoldi3r
PsykoSoldi3r

Reputation: 429

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

Upvotes: 12

Views: 9256

Answers (5)

Yang
Yang

Reputation: 998

What about using date.getMilliseconds() ?

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

console.log(date.toLocaleString() + " " + date.getMilliseconds()); 
//3-12-2018 17:24:05 ???

Upvotes: 3

Adán Escobar
Adán Escobar

Reputation: 4613

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());

Upvotes: 9

Hemera
Hemera

Reputation: 55

As mentioned a keyword for milliseconds is missing.
I built a javascript clock for practise and run into the same problem but I already built an interface for toLocaleString so I decide to add my own feature that probably won't work with all languages but it's good enough.
I choose millisecond as keyword. I think as format information a combination of using n-digit like 2-digit and anything for no specific millisecond format (cause also include numeric) would be enough.
As connection I use colon when the format of hourCycle is defined as h23 or h24 and space else.

(Code in snippet without error handling, trigger is onchange so fill in en and than change hourCycle to h11)

function toLocalStringFromDate(nDate, nLanguage, nOptions){
    if("millisecond" in nOptions){ // own keyword option
        if(nOptions.millisecond.endsWith("-digit")){
            let tDigits = parseInt(nOptions.millisecond.substring(0, nOptions.millisecond.length-6));
            // extract amount of digits from format
            let tLength = (""+nDate.getMilliseconds()).length;
            // length of current milliseconds
            return nDate.toLocaleString(nLanguage, nOptions)
                // basic formatting
                +("hourCycle" in nOptions && (nOptions.hourCycle == "h23" || nOptions.hourCycle == "h24") ? ':' : ' ')
                // separator
                +("0".repeat(tDigits)+nDate.getMilliseconds()).substring(tLength, tDigits+tLength);
                // n-digit of zeros followed by milliseconds shifted by n digit is substring(tDigits+tLength-tDigits, tDigits+tLength);
        }
        else{
            return nDate.toLocaleString(nLanguage, nOptions)+("hourCycle" in nOptions && (nOptions.hourCycle == "h23" || nOptions.hourCycle == "h24") ? ':' : ' ')+nDate.getMilliseconds();
        }
    }
    else{
        return nDate.toLocaleString(nLanguage, nOptions);
    }
}

window.document.body.children[1].lastElementChild.value = "{\"hourCycle\": \"h23\", \"millisecond\": \"3-digit\"}";
input{width: 60%;}
<p><b>Language: </b><input onchange="console.log(toLocalStringFromDate(new Date(), this.value, JSON.parse(this.parentElement.nextElementSibling.lastElementChild.value)));"></p>
<p><b>Options: </b><input onchange="console.log(toLocalStringFromDate(new Date(), this.parentElement.previousElementSibling.lastElementChild.value, JSON.parse(this.value)));"></p>

Upvotes: 0

Tina Gordienko_Drog
Tina Gordienko_Drog

Reputation: 335

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

console.log(result);

Upvotes: 0

Jyotirmoy Upadhaya
Jyotirmoy Upadhaya

Reputation: 545

You can achieve this with the following lines of code

const date = new Date();
const localDateTime = date.toLocaleString();
const currentDateObj = new Date(localDateTime); 
const convertLocalDateTimeToMS = currentDateObj.getTime(); 
console.log(convertLocalDateTimeToMS); // 1630060060000

Upvotes: -2

Related Questions