时间戳
指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。通俗的讲, 时间戳是一份能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据。
时区
由于世界各国家与地区经度不同,地方时也有所不同,因此会划分为不同的时区。正式的时区划分,其中包括24个时区,每一时区由一个英文字母表示。同一时刻,各个地区的本地时间是不同的。
总结
不同的时区时间不同,但时间戳具有时区无关性,这时候就需要涉及到转换到当地时间格式,以及当地时区哪一天等
以下计算某个时间戳的本地当天时间(秒),时间戳是根据0时区为基准的,所以计算n时区当天开始时间,需要加上n * 3600,最后计算到天数后还需要减去n * 3600
function getLocalDaySecord(time, timezone) {
const day = Math.floor((time + timezone * 3600) / (24 * 3600));
const sec = day * 24 * 3600 - timezone * 3600;
return sec;
}
获取某个时区的日期: 20200101010101
const TIMEZONE = -new Date().getTimezoneOffset() / 60; //本地时区
function getLocalDateString(time, timezone) {
let offset = 0;
if (timezone !== undefined) {
offset = (timezone - TIMEZONE) * 3600 * 1000;
}
if (time === undefined) {
time = Date.now();
}
const date = new Date(time + offset);
const year = date.getFullYear(); //年
const month = date.getMonth() + 1; //天
const day = date.getDate(); //day-of-the-month
// var days = date.getDay(); //day-of-the-weak
const hours = date.getHours(); //小时
const minutes = date.getMinutes(); //分钟
const seconds = date.getSeconds(); //秒
//const ms = date.getMilliseconds();//毫秒
const d1 = year * 10000 + month * 100 + day;
const d2 = hours * 10000 + minutes * 100 + seconds;
return d1 + '' + d2;
};
网友评论