【发布时间】:2023-03-23 14:38:01
【问题描述】:
我已经尝试寻找答案,虽然我找到了非常相似的答案,但我不认为它们正是我想要的。如果这已经在其他地方得到回答,请原谅我。
我正在尝试在 javascript 中解析 ISO 日期,以便我可以将其与客户端系统日期进行比较,并根据 ISO 日期是在客户端系统日期之前还是之后显示信息。
这很好,直到我需要支持 IE8,现在我被卡住了。
我创建了一个函数,因为我需要对三个不同的日期执行此操作。
例如,我的 ISO 日期是:UTC 时间的 2015-12-22T11:59。
但是一旦我的日期被解析,完整的日期是当地时间 11:59,无论我测试哪个时区,在那个时区它总是 11.59。
我知道我当前创建的函数对时区没有任何作用,这就是我卡住的地方。我不知道要添加什么来更改我的结束日期以反映客户端机器的时区。
任何帮助或建议将不胜感激。 因为我有上传限制,所以我无法使用诸如 moment.js 之类的东西。
Jquery 是可用的。或纯javascript。
<script>
function setSaleContent() {
//creating a new date object that takes the clients current system time. so we can compare it to the dates stored in our array
var currentDate = new Date();
console.log(currentDate + " this is the clients date ");
//These variables actually come from an external array object, but I'm putting them in here like this for this example.
var destinations = {
freedate: "2015-12-16T11:59",
courierdate: "2015-12-22T11:59",
nextdaydate: "2015-12-23T11:59",
}
//fetch all the ISO dates from the array.
var freeDateISO = destinations["freedate"];
var courierDateISO = destinations["courierdate"];
var nextdayDateISO = destinations["nextdaydate"];
//I am creating this reusable function to split up my ISO date for the sake of IE8.. and create it into a date format that can be compared against another date. I know that this isn't doing anything with my timezone and that is where my problem lies.
function parseDate(str) {
var parts = /^(\d{4}).(\d{2}).(\d{2}).(\d{2}):(\d{2})/.exec(str);
if (parts) {
return new Date(parts[1], parts[2] - 1, parts[3], parts[4], parts[5]);
}
return new Date();
}
//I would like this date to change to reflect the time zone of the clients system time.
//currently returns the date at 11.59 regardless of timezone.
//If i was in GMT i would want it to say 11.59
//If i was in CT time I would like this to say 05.59
//If i was in Perth I would like this to say 19:59
var freeDate = parseDate(freeDateISO);
console.log(freeDate + " this is the converted date for IE")
}
window.onload = setSaleContent;
【问题讨论】:
-
不要使用
new Date(…)(从本地值创建日期时间),使用new Date(Date.UTC(…))作为UTC值!
标签: javascript jquery date parsing iso