最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Date to localeString with milliseconds? - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited Nov 14, 2021 at 2:44 kmoser 9,2733 gold badges26 silver badges44 bronze badges asked Dec 3, 2018 at 16:26 PsykoSoldi3rPsykoSoldi3r 4291 gold badge4 silver badges17 bronze badges 10
  • Please share the code that you have already tried. – lloydaf Commented Dec 3, 2018 at 16:28
  • Added the code to the question – PsykoSoldi3r Commented Dec 3, 2018 at 16:31
  • you need to use a library like moment.js – Daniel A. White Commented Dec 3, 2018 at 16:36
  • 1 @theapologist I want a locale string with milliseconds. Not to convert a date to milliseconds. – PsykoSoldi3r Commented Dec 3, 2018 at 16:40
  • 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 Commented Dec 3, 2018 at 16:44
 |  Show 5 more comments

5 Answers 5

Reset to default 9

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

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 ???

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

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>

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

发布评论

评论列表(0)

  1. 暂无评论