JS将指定的时间戳转为UTC时间

时间:2023-07-19 16:35:32

  Js中获取时间戳可用var dayMiliseconds = parseInt(new Date().valueOf());Js的时间戳单位为毫秒(1s = 1000 ms),下面是一个将制定的格式转化成UTC时间的函数。

//format the date string from webservice to UTC time;
function toUTCtime(dateStr) {
//Date(1381243615503+0530),1381243615503,(1381243615503+0800) dateStr += "";
var utcPrefix = 0;
var offset = 0;
var dateFormatString = "yyyy-MM-dd hh:mm:ss";
var utcTimeString = "";
var totalMiliseconds = 0; var regMatchNums = /\d+/gi;
var regSign = /[\+|\-]/gi;
var arrNums = dateStr.match(regMatchNums);
utcPrefix = parseInt(arrNums[0]);
if (arrNums.length > 1) {
offset = arrNums[1];
offsetHour = offset.substring(0, 2);
offsetMin = offset.substring(2, 4);
offset = parseInt(offsetHour) * 60 * 60 * 1000 + parseInt(offsetMin) * 60 * 1000;
}
if(dateStr.lastIndexOf("+")>-1){
totalMiliseconds= utcPrefix - offset;
} else if (dateStr.lastIndexOf("-") > -1) {
totalMiliseconds = utcPrefix + offset;
} utcTimeString = new Date(totalMiliseconds).format(dateFormatString);
return utcTimeString; }