从GMT时间转换到当地时间(北京时间)

项目中,需要把服务器中传过来的字符串时间信息(GMT)转化为北京时间(+8小时)。

把字符串时间转化为JS的Date类型(Date.UTC),加上时差毫秒数,用setTime()方法把毫秒数再转化为Date类型。再从该Date类型解析具体日期和时间。

如,传过来的时间信息为 "2011-11-17T01:39:40.709Z",最终显示时间为 "11月17日  01:39"。

var dateBefore = $time.slice(0,10);

var timeBefore = $time.slice(11,19);

var dateArray = dateBefore.split("-");
var timeArray = timeBefore.split(":");

//注意,Date对象中的getMonth() 返回0~11

var feedDate = Date.UTC(dateArray[0],dateArray[1]-1,dateArray[2],timeArray[0],timeArray[1],timeArray[2],0) + 8*60*60;
var now = new Date();
now.setTime(feedDate);

if (now.getMonth()<10){
var month = "0" + now.getMonth()+1;
}else{
var month = now.getMonth()+1;
}

if (now.getDate()<10){
var date = "0" + now.getDate();
}else{
var date = now.getDate();
}
//var dateAfter = now.getFullYear() + "-" + month + "-" + date;
var dateAfter = month + "月" + date + "日";

if (now.getHours()<10){
var hour = "0" + now.getHours();
}else{
var hour = now.getHours();
}

if (now.getMinutes()<10){
var minute = "0" + now.getMinutes();
}else{
var minute = now.getMinutes();
}
var timeAfter = hour + ":" + minute;
var timeFinal = dateAfter + "  " + timeAfter;
return timeFinal;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值