js将UTC时间转化为当地时区时间 用JS将指定时间转化成用户当地时区的时间
参考:https://www.cnblogs.com/catgatp/p/13178934.html
用JS将指定时间转化成用户当地时区的时间:
参考:https://www.cnblogs.com/simendancer/p/5165023.html
容易理解:
https://blog.csdn.net/u012193330/article/details/79637660?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~baidu_landing_v2~default-1-79637660.nonecase&utm_term=js0%E6%97%B6%E5%8C%BA%E7%9A%84%E6%97%B6%E9%97%B4%E8%BD%AC%E5%8C%96%E4%B8%BA%E5%BD%93%E5%9C%B0%E6%97%B6%E9%97%B4
js获取时区:
https://blog.csdn.net/qawser7335527/article/details/80179223
var d = new Date(); var local = d.getTime(); var offset = d.getTimezoneOffset() * 60000; var localUtc = new Date().getTimezoneOffset() / 60; var utcTime; if (localUtc > 0) { utcTime = local - offset; } else { utcTime = local + offset; } console.log("localUtc: " + localUtc); var localTime = utcTime + 3600000 * Math.abs(localUtc); console.log("localTime: " + localTime); var nd = new Date(localTime); var YY = nd.getFullYear() + "年"; var MM = nd.getMonth() + 1 + "月"; var dd = nd.getDate() + "日"; var hh = nd.getHours() + ":"; var mm = nd.getMinutes() + ":"; var ss = nd.getSeconds(); console.log(YY + MM + dd + hh + mm + ss);
获取当前时区的简单代码:
console.log(new Date().getTimezoneOffset()/60) // -8
已知目标时区,根据本地时间获取目标时区的时间:
方法1:
var timezone = 8; //目标时区时间,东八区 var offset_GMT = new Date().getTimezoneOffset(); // 本地时间和格林威治的时间差,单位为分钟 var nowDate = new Date().getTime(); // 本地时间距 1970 年 1 月 1 日午夜(GMT 时间)之间的毫秒数 var targetDate = new Date( nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000 ); console.log("东8区现在是:" + targetDate);
方法2(目前使用的):
// 将传入的时间转换为new Date时间格式 const toDate = new Date("2020-09-10 06:26:59"); console.log(toDate.getHours()); var d = toDate; var localTime = d.getTime(); var localOffset = d.getTimezoneOffset() * 60000; //getTimezoneOffset()返回是以分钟为单位,需要转化成ms var utc = localTime + localOffset; var offset = 9; //以韩国时间为例,东9区 var korean = utc + 3600000 * offset; var nd = new Date(korean); console.log("Korean time is " + nd.toLocaleString()); // Korean time is 2020/9/10 上午7:26:59
记录自己的采坑之路,需要时方便查找