我正在将时间戳传递给下面的函数,它正在正确地返回日期字符串,但是当我在行下面执行时它会给我错误的无效日期。
var postDate = new Date(this.ConvertServerDateToLocal(timestamp));
//postDate returns invalid date object.
ConvertServerDateToLocal: function(dateInput){
// EST - UTC offset: 4 hours
var offset = 4.0,
/*
- calculate the difference between the server EST date and UTC
- the value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
- the time-zone offset is the difference, in minutes, between UTC and local time
- 60000 milliseconds = 60 seconds = 1 minute
*/
serverDate = new Date(dateInput),
utc = serverDate.getTime() - (serverDate.getTimezoneOffset() * 60000),
/*
- apply the offset between UTC and EST (4 hours)
- 3600000 milliseconds = 3600 seconds = 60 minutes = 1 hour
*/
clientDate = new Date(utc + (3600000 * offset));
return clientDate.toLocaleString();
}
下面是我传递给ConvertServerDateToLocal()函数的示例时间戳。
timestamp =" 2017年11月22日23:05:58" //输出
后抛出无效日期timestamp =" 2017年11月9日18:30:19" //正常工作
答案 0 :(得分:0)
function ConvertServerDateToLocal(dateInput) {
// EST - UTC offset: 4 hours
dateInput = "Nov 09, 2017 18:30:19";
var offset = 4.0,
/*
- calculate the difference between the server EST date and UTC
- the value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
- the time-zone offset is the difference, in minutes, between UTC and local time
- 60000 milliseconds = 60 seconds = 1 minute
*/
serverDate = new Date(dateInput.toString());
utc = serverDate.getTime() - (serverDate.getTimezoneOffset() * 60000);
/*
- apply the offset between UTC and EST (4 hours)
- 3600000 milliseconds = 3600 seconds = 60 minutes = 1 hour
*/
clientDate = new Date(utc + (3600000 * offset));
//return clientDate.toLocaleString();
alert(clientDate.toLocaleString());
}
将输入参数转换为字符串对我有用。但我不确定为什么一个日期有效,另一个日期不起作用。如果您找到答案,请在此处发布。我也经常使用日期,他们总是很痛苦。