1、把客户端时间转换为北京时间
function getBeijingtime() { //获得当前运行环境时间 var d = new Date(); currentDate = new Date(); tmpHours = currentDate.getHours(); //算得时区 var time_zone = -d.getTimezoneOffset() / 60; if (time_zone < 0) { time_zone = Math.abs(time_zone) + 8; currentDate.setHours(tmpHours + time_zone); } else { time_zone -= 8; currentDate.setHours(tmpHours - time_zone); } return currentDate; }
讯享网
new Date() 方法返回的是本机时间,是带时区的时间。导入参数后返回的是带时区的日期与1970年1月1日相差的毫秒数;
getTimezoneOffset() 方法可返回格林威治时间和本地时间之间的时差,以分钟为单位。
2、获取时间戳
讯享网function getTimeStamp(){ const currentDate = getBeijingtime(); const y = currentDate.getFullYear(); //当前客户端对应的北京时间的年 const m = currentDate.getMonth(); //北京时间的月 const d = currentDate.getDate(); const h = currentDate.getHours(); const mm = currentDate.getMinutes(); const ss = currentDate.getSeconds(); // Date.UTC() 方法接受的参数同日期构造函数接受最多参数时一样,返回从1970-1-1 00:00:00 UTC到指定日期的的毫秒数。 const timeObj =Date.UTC(y, m, d, h, mm, ss, 0) / 1000 - (8 * 60 * 60); return timeObj; }
而Date.UTC()返回的是0时区的时间,返回的是0时区的当前日期与1970.1.1相差的毫秒数。那么它与北京时间差值就是固定的8小时;

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/55068.html