[英]A javascript function returns different results in Chrome and Firefox
I've found a very interesting issue while working with Date in React.在 React 中使用 Date 时,我发现了一个非常有趣的问题。
Here is the function:这是 function:
const formatDate = (orderDate) => {
const date = new Date(orderDate);
const day = date.getDay();
const month = date.toLocaleString('default', { month: 'long' });
const year = date.getFullYear();
return `${day}-${month.slice(0, 3)}-${year}`;
};
it receives a date as parameter, in my case, orderDate = "05-Feb-2021 06:29:33 PM";
它接收一个日期作为参数,在我的例子中,
orderDate = "05-Feb-2021 06:29:33 PM";
If you run this in Chrome dev tools, it returns the desired result: "5-Feb-2021"
如果您在 Chrome 开发工具中运行它,它会返回所需的结果:
"5-Feb-2021"
But in Mozilla Firefox, the same operation returns this: "1-Feb--2021"
但在 Mozilla Firefox 中,相同的操作返回:
"1-Feb--2021"
Why is this happening and how can it be avoided?为什么会发生这种情况,如何避免?
Why is this happening and how can it be avoided?
为什么会发生这种情况,如何避免?
This is happening because it is left to the agent how non ISO strings are parsed.发生这种情况是因为如何解析非 ISO 字符串由代理决定。 This is not defined in the language specification.
这在语言规范中没有定义。
MDN explains and warns about this: MDN 对此进行了解释和警告:
Implicit call:
隐式调用:
new Date(dateString)
[...]
[...]
If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm.
如果字符串不符合标准格式,则 function 可能会退回到任何特定于实现的启发式或特定于实现的解析算法。
So either you need to provide the string in ISO format, or (better) you call the Date
constructor with individual, numerical values for each component of the date/time.因此,要么您需要提供 ISO 格式的字符串,要么(更好)调用
Date
构造函数,并为日期/时间的每个组成部分提供单独的数值。
Firefox does not like the - in dateString. Firefox 不喜欢 dateString 中的 -。
Replace all occurrences of - with / using a regular expression and then convert the string to Date object.使用正则表达式将所有出现的 - 替换为 /,然后将字符串转换为 Date object。
const formatDate = (orderDate) => {
const date = new Date(orderDate.replace(/-/g, "/"));
const day = date.getDate();
const month = date.toLocaleString("default", { month: "long" });
const year = date.getFullYear();
return `${day}-${month.slice(0, 3)}-${year}`;
};
Side Note: The arguments you provide to new Date should be numbers, not strings.旁注:您提供给新日期的 arguments 应该是数字,而不是字符串。 Although the date constructor will coerce for you, it's best practice not to rely on it.
尽管日期构造函数会为您强制执行,但最好不要依赖它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.