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

date.toLocaleString(options) does not work javascript - Stack Overflow

programmeradmin1浏览0评论

I am quite new to JS and need some help.

I want to format date with the help of toLocaleString(). According to standards first argument 'locales' can be omitted. My code looks like:

    let myDate = new Date(2014, 0, 30)
    let options = {
                year: '2-digit',
                month: '2-digit',
                day: '2-digit'
            };
    let formattedDate = myDate.toLocaleString(options);
    
    console.log(formattedDate);

I am quite new to JS and need some help.

I want to format date with the help of toLocaleString(). According to standards first argument 'locales' can be omitted. My code looks like:

    let myDate = new Date(2014, 0, 30)
    let options = {
                year: '2-digit',
                month: '2-digit',
                day: '2-digit'
            };
    let formattedDate = myDate.toLocaleString(options);
    
    console.log(formattedDate);

Share Improve this question edited May 10, 2017 at 15:04 Scott Marcus 65.8k6 gold badges53 silver badges80 bronze badges asked May 10, 2017 at 14:48 lessismorelessismore 1771 gold badge1 silver badge9 bronze badges 1
  • You need to pass a locale to toLocaleString. Use this let formattedDate = date.toLocaleString('en-US', options); – alfredo Commented May 10, 2017 at 14:56
Add a comment  | 

3 Answers 3

Reset to default 8

While you can skip the first argument, without supplying something for it in your case, you won't get the options argument to give you the results you want.

Here are a few versions of working code:

let date = new Date(2014, 0, 30);

let options = {
            year: '2-digit',
            month: '2-digit',
            day: '2-digit'
        };

console.log(date.toLocaleString('en-us', options));
console.log(date.toLocaleString(undefined, options));
console.log(date.toLocaleString(options));

options.timeZone = 'UTC';
options.timeZoneName = 'short';

console.log(date.toLocaleString('en-US', options));


// sometimes even the US needs 24-hour time
console.log(date.toLocaleString('en-US', { hour12: false }));

The first argument to toLocaleString is not optional, but you can pass undefined to it.

let date = new Date(2014, 0, 30)
let options = {
            year: '2-digit',
            month: '2-digit',
            day: '2-digit'
        };
let formattedDate = date.toLocaleString(undefined, options);
console.log(formattedDate);

You should use the options as second parameter:

let date = new Date(2014, 2, 2)
let options = {
            year: '2-digit',
            month: '2-digit',
            day: '2-digit'
        };
let formattedDate = date.toLocaleString(undefined, options);
发布评论

评论列表(0)

  1. 暂无评论