【发布时间】:2022-01-26 02:53:19
【问题描述】:
我们有一个日期格式化功能,它似乎会根据浏览器生成不同的日期。该函数有两个步骤,首先确定用户的日期格式,然后相应地格式化日期。
// determine date string format for PrettyDate functions
var dtstr;
var dtsep;
let customDate = new Date(2222, 11, 18);
let strDate = customDate.toLocaleDateString();
let daTyp = strDate.substring(0, 2);
if (daTyp === '22') {
dtstr = 'YMD';
dtsep = ',';
}
else if (daTyp === '12') {
dtstr = 'MDY';
dtsep = ';';
}
else {
dtstr = 'DMY';
dtsep = ',';
}
// make dates human readable
function prettyDate(datestr, use) {
var date = new Date(datestr);
if (!isNaN(date.getTime())) {
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const monthCount = date.getMonth();
const theMonth = monthNames[monthCount];
const theYear = date.getFullYear();
const theDay = date.getDate();
if (use === 'short') {
if (dtstr === 'MDY') {
return theMonth + ' ' + theDay;
}
else {
return theDay + ' ' + theMonth;
}
}
else {
if (dtstr === 'YMD') {
return datestr;
}
else if (dtstr === 'MDY') {
return theMonth + ' ' + theDay + ', ' + theYear;
}
else {
return theDay + ' ' + theMonth + ' ' + theYear;
}
}
}
}
被转换的datestr 的格式为 2022-08-17,use 的值是“短”或“长”。
我们在可以访问的计算机上进行的所有检查都显示结束日期为 2022 年 8 月 17 日或 2022 年 8 月 17 日。但我们有几个网站用户报告他们得到的是 2022 年 8 月 16 日或 2022 年 8 月 16 日。
更新
已尝试使用计算机时区进行一些实验,但似乎确实有影响。那么新的紧迫问题是我们如何修改代码以防止操作系统时区影响结果?
对计算机时区设置的进一步试验表明,如果时区为 UTC +XX:00,则显示的日期是正确的。如果是 UTC -XX:00,则日期提前一天。
终于
我正式授予自己当天的 Dunderhead 奖。我的datestr 基本上是一个字符串,所以只需使用split() 并改造部分。多么设计过度的菜鸟之举。
function prettyDate(datestr, use) {
const dtparts = String(datestr).split('-');
const monthNames = ["","Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const monthCount = +dtparts[1];
const theMonth = monthNames[monthCount];
const theYear = dtparts[0];
const theDay = dtparts[2];
... previous code
}
感谢那些试图提供帮助的人。
【问题讨论】:
-
你确定这与你同时测试的机器的时区没有任何关系吗?
-
@esqew - 时区将如何影响 JS?
datestr值来自我们服务器上的数据库。 -
您使用的是同一个浏览器吗?看到这个帖子:stackoverflow.com/questions/3552461/…
-
@code - 我已经成功尝试了多个浏览器。一位报告该问题的网站访问者在 Win 11 上尝试了几种浏览器,Edge 显示了正确的日期,Firefox 显示了错误的日期,Win10 上的 Edge 显示了错误的日期。这是一个树桩..
-
不确定它是否与
datestr格式有关,但请尝试将它们格式化为2022/08/17而不是使用连字符-,因为这在某些浏览器中似乎存在一些解析问题:dygraphs.com/date-formats.html
标签: javascript date