11

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
kmoser
  • 8,780
  • 3
  • 24
  • 40
PsykoSoldi3r
  • 409
  • 1
  • 4
  • 17
  • Please share the code that you have already tried. – lloydaf Dec 03 '18 at 16:28
  • Added the code to the question – PsykoSoldi3r Dec 03 '18 at 16:31
  • you need to use a library like moment.js – Daniel A. White Dec 03 '18 at 16:36
  • I've converted your code to a snippet, as with `toLocaleString()` it's always important to consider that each user's output will be different. That said, I don't think this really changes your question all that much. – Tyler Roper Dec 03 '18 at 16:36
  • 1
    @theapologist I want a locale string with milliseconds. Not to convert a date to milliseconds. – PsykoSoldi3r Dec 03 '18 at 16:40
  • Should format the string yourself using the various Date methods. `toLocaleString()` produces different formats in different locales. Or use a date library – charlietfl Dec 03 '18 at 16:40
  • @PsykoSoldi3r sorry, misunderstood your question. – lloydaf Dec 03 '18 at 16:41
  • 2
    I don't think you can do this with `toLocaleString()`, as there is no native `option` for it, nor is the output consistent enough across locales to simply concatenate the milliseconds. For example, my output ends in `AM`, whereas yours ends in the time of day. – Tyler Roper Dec 03 '18 at 16:44
  • Yes, it’s possible but you’ll have to construct the string using an options argument, format the parts and add them yourself. – RobG Dec 03 '18 at 20:58
  • Probably a duplicate of [*How to format a JavaScript date*](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) and many others. – RobG Dec 03 '18 at 23:05

5 Answers5

7

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());
Adán Escobar
  • 1,729
  • 9
  • 15
2

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 ???
Yang
  • 618
  • 6
  • 9
0

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

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>
Hemera
  • 55
  • 1
  • 9
-1

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
  • 1
    `currentDateObj` is an invalid date. Locale strings cannot always be parsed back to a Date object. – Seblor Aug 27 '21 at 10:40
  • Can you show me where it is showing as an invalid date. – Jyotirmoy Upadhaya Aug 27 '21 at 11:26
  • Sure, running your 3 first lines in France makes `currentDateObj` an invalide date, thus making your snippet show `NaN`. The value of `localDateTime` is "27/08/2021, 18:23:11". – Seblor Aug 27 '21 at 16:22