toLocaleDateString Javascript 日期格式问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17459697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:25:28  来源:igfitidea点击:

toLocaleDateString Javascript date format issues

javascriptstringdatedatetimecross-browser

提问by MJCoder

I've got a script and i want to format a date out to short date format ie:

我有一个脚本,我想将日期格式化为短日期格式,即:

7/3/2013 or 7/3/13 the first date format renders like that in Chrome but every other browser it does not - it displays the date month name and the year.

2013 年 7 月 3 日或 7 月 3 日第一个日期格式在 Chrome 中呈现,但其他所有浏览器都没有 - 它显示日期月份名称和年份。

function dateFormatter(date) {
  return date.toLocaleDateString();
}

Bit confused as to why this is happening. Is it because that browser doesnt support tolocalDateString();

有点困惑为什么会这样。是不是因为那个浏览器不支持 tolocalDateString();

Would i need to build a custom date string in order for it to work?

我是否需要构建自定义日期字符串才能使其正常工作?

Sorry if its a little vague - I've had a look on W3C website but dont trust that site at times.

对不起,如果它有点含糊 - 我看过 W3C 网站,但有时不信任该网站。

采纳答案by kennebec

function dateFormatter(date){
    if(Date.parse('2/6/2009')=== 1233896400000){
        return [date.getMonth()+1, date.getDate(), date.getFullYear()].join('/');
    }
    return [date.getDate(), date.getMonth()+1, date.getFullYear()].join('/');
}

回答by Koterpillar

The default format of toLocaleDateStringis implementation-defined. If you want precise control of what's displayed, use a browser supporting localesand optionsargumentsto toLocaleDateString. Unfortunately, at the moment that means only Chrome.

的默认格式toLocaleDateString是实现定义的。如果你想的钱包显示的精确控制,使用浏览器支持localesoptions论据toLocaleDateString。不幸的是,目前这意味着只有 Chrome。

If you don't care about the user and their locale and would like to confuse everyone with US date format, then yes, you can hardcode the date parts as @kennebec suggested.

如果您不关心用户和他们的语言环境,并希望将每个人与美国日期格式混淆,那么是的,您可以按照 @kennebec 的建议对日期部分进行硬编码。