本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342.html
常用JS封装方法传预告:
- 项目常用JS方法封装(三) [ 字符串相关处理 ]
- 项目常用JS方法封装(四) [ 数组相关处理 ]
使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!
001.时间戳转化成YMD格式
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
* timestamp 当前时间戳,毫秒
* formats 时间格式,包括:
* 1. Y-m-d
* 2. Y-m-d H:i:s
* 3. Y年m月d日
* 4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return `${y}`;
}
console.log(dateY(date));
复制代码
003.年月
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return `${y}-${m}`;
}
console.log(dateYM(date));
复制代码
004.年月日
可根据自己需求,自己添加或删除相应的时间
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return `${y}-${m}-${d}`;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return `${y}-${M}-${d} ${h}:${m}:${s}`;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = `${s}秒前`
} else if (m >= 1 && h < 1) {
msg = `${m}分钟前`;
} else if (h >= 1 && h <= 24) {
msg = `${h}小时前`;
} else if (h > 24) {
h = parseInt(h / 24)
msg = `${h}天前`;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/***参数都是以周一为基准的***/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
以下代码写到HTML的body中
<span id="clock">00:01:00:00</span>
<input id="start" type="button" value="开始" onclick="run()">
<input id="end" type="button" value="结束" onclick="stop()">
<input id="reset" type="button" value="重置" onclick="reset()">
<script language="Javascript">
var normalelapse = 100;
var nextelapse = normalelapse;
var counter;
var startTime;
var start = clock.innerText;
var defaultTime = clock.innerText;
var finish = "00:00:00:00";
var timer = null;
// 开始运行
function run() {
start.disabled = true;
end.disabled = false;
reset.disabled = false;
counter = 0;
// 初始化开始时间
startTime = new Date().valueOf();
// nextelapse是定时时间, 初始时为100毫秒
// 注意setInterval函数: 时间逝去nextelapse(毫秒)后, onTimer才开始执行
timer = window.setInterval("onTimer()", nextelapse);
}
// 停止运行
function stop() {
start.disabled = false;
end.disabled = true;
reset.disabled = true;
window.clearTimeout(timer);
}
window.onload = function () {
end.disabled = true;
};
// 重置时间
function reset() {
start.disabled = true;
end.disabled = false;
reset.disabled = false;
window.clearTimeout(timer);
clock.innerText = defaultTime
}
// 倒计时函数
function onTimer() {
if (start == finish) {
window.clearInterval(timer);
alert("时间到了!");
return;
}
var hms = new String(start).split(":");
var ms = new Number(hms[3]);
var s = new Number(hms[2]);
var m = new Number(hms[1]);
var h = new Number(hms[0]);
ms -= 10;
if (ms < 0) {
ms = 90;
s -= 1;
if (s < 0) {
s = 59;
m -= 1;
}
if (m < 0) {
m = 59;
h -= 1;
}
}
var ms = ms < 10 ? ("0" + ms) : ms;
var ss = s < 10 ? ("0" + s) : s;
var sm = m < 10 ? ("0" + m) : m;
var sh = h < 10 ? ("0" + h) : h;
start = sh + ":" + sm + ":" + ss + ":" + ms;
clock.innerText = start;
// 清除上一次的定时器
window.clearInterval(timer);
// 自校验系统时间得到时间差, 并由此得到下次所启动的新定时器的时间nextelapse
counter++;
var counterSecs = counter * 100;
var elapseSecs = new Date().valueOf() - startTime;
var diffSecs = counterSecs - elapseSecs;
nextelapse = normalelapse + diffSecs;
if (nextelapse < 0) nextelapse = 0;
// 启动新的定时器
timer = window.setInterval("onTimer()", nextelapse);
}
</script>
复制代码
011.计时器(无开始结束)
以下代码写到HTML的body中
<div id="time"></div>
<script type="text/javascript">
var maxtime = 10 * 60; //
function CountDown() {
if (maxtime >= 0) {
minutes = Math.floor(maxtime / 60);
seconds = Math.floor(maxtime % 60);
msg = "还有" + minutes + "分" + seconds + "秒";
document.all["time"].innerHTML = msg;
if (maxtime == 5 * 60) alert("仅剩5分钟");
--maxtime;
} else {
clearInterval(timer);
alert("时间到!");
}
}
timer = setInterval("CountDown()", 1000);
</script>
复制代码
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6342/
![手把手教你常用JS方法封装(二)-时间方法](http://p3.pstatp.com/large/dfic-imagehandler/22cd14ed-357d-46b3-83ad-4b8dd6e17aa6)
常用JS封装方法传预告:
* 项目常用JS方法封装(三) [ 字符串相关处理 ]
* 项目常用JS方法封装(四) [ 数组相关处理 ]
* * *
**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**
001.时间戳转化成YMD格式
===============
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
/*
- timestamp 当前时间戳,毫秒
- formats 时间格式,包括:
-
1. Y-m-d
-
2. Y-m-d H:i:s
-
3. Y年m月d日
-
4. Y年m月d日 H时i分s秒
*/
dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minite = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(date,'Y-m-d'));
复制代码
002.年
=====
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateY = time =>{
let newDate = new Date(time);
let {y}={y:newDate.getFullYear()};
return ${y}
;
}
console.log(dateY(date));
复制代码
003.年月
======
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateYM = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}
;
}
console.log(dateYM(date));
复制代码
004.年月日
=======
**可根据自己需求,自己添加或删除相应的时间**
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateymd = time => {
let newDate = new Date(time);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return ${y}-${m}-${d}
;
}
console.log(dateymd2(date));
复制代码
005.年月日时分秒
==========
let date = Date.parse(new Date()) // 获取当前时间戳(毫秒)
dateTime = time => {
let newDate = new Date(time);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return ${y}-${M}-${d} ${h}:${m}:${s}
;
}
console.log(dateTime(date));
复制代码
006.计算时间N之前
===========
time_filter = time => {
time -= 0;
let difTime = new Date().getTime() - time;
let { h, m, s } = { h: parseInt(difTime / (3600 * 1000)), m: parseInt(difTime / (60 * 1000)), s: parseInt(difTime / 1000) };
let msg = "";
if (m < 1) {
msg = ${s}秒前
} else if (m >= 1 && h < 1) {
msg = ${m}分钟前
;
} else if (h >= 1 && h <= 24) {
msg = ${h}小时前
;
} else if (h > 24) {
h = parseInt(h / 24)
msg = ${h}天前
;
}
return msg;
}
//输入一个时间戳,能计算出来是多长时间之前
console.log(time_filter(1584009520000)); //3分钟前
复制代码
007.获取上周本周下周时间
==============
getDate = n => {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let day = now.getDay();
if (day !== 0) {
n = n + (day - 1);
} else {
n = n + day;
}
if (day) {
if (month > 1) {
month = month;
} else {
year = year - 1;
month = 12;
}
}
now.setDate(now.getDate() - n);
year = now.getFullYear();
month = now.getMonth() + 1;
date = now.getDate();
let s =
year +
"-" +
(month < 10 ? "0" + month : month) +
"-" +
(date < 10 ? "0" + date : date);
return s;
}
/参数都是以周一为基准的/
//上周的开始时间
// console.log(getDate(7));
//上周的结束时间
// console.log(getDate(1));
//本周的开始时间
// console.log(getDate(0));
//本周的结束时间
// console.log(getDate(-6));
//下周的开始时间
// console.log(getDate(-7));
//下周结束时间
// console.log(getDate(-13));
复制代码
008.获取当前时间(年月日)
===============
getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
复制代码
009.当前的时间(年月日时分秒)
=================
getDateTime = () => {
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours() + 1;
minute = date.getMinutes();
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
console.log(getDateTime());
复制代码
010.倒计时(开始结束重置,自定义时间)
=====================
**以下代码写到HTML的body中**
00:01:00:00
复制代码
011.计时器(无开始结束)
==============
**以下代码写到HTML的body中**
复制代码
```
012.获取最近一周(月),下一周(月)日期范围
使用时要注意函数之间的相互引用和this指向问题
/*
* @param dateNow :Date类
* @param intervalDays :间隔天数
* @param bolPastTime :Boolean,判断在参数date之前,还是之后,
*/
getDateRange = (dateNow, intervalDays, bolPastTime) => {
let oneDayTime = 24 * 60 * 60 * 1000;
let list = [];
let lastDay;
if (bolPastTime === true) {
lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
list.push(formateDate(lastDay));
list.push(formateDate(dateNow));
} else {
lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
list.push(formateDate(dateNow));
list.push(formateDate(lastDay));
}
return list;
}
function formateDate (time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let day = time.getDate()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return year + '-' + month + '-' + day + ''
}
var date = new Date();
var list = getDateRange(date, 6, true)
console.log("获取近一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, true)
console.log("获取近一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 0, true)
console.log("获取今天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 1, true)
console.log("获取昨天日期范围:
开始日期:" + list[0] + ";结束日期:" + list[0]);
var list = getDateRange(date, 6, false)
console.log("获取下一周日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
var list = getDateRange(date, 30, false)
console.log("获取下一个月日期范围:
开始日期:" + list[0] + ";结束日期:" + list[1]);
/*
获取近一周日期范围:
开始日期:2019-12-04;结束日期:2019-12-10
获取近一个月日期范围:
开始日期:2019-11-10;结束日期:2019-12-10
获取今天日期范围:
开始日期:2019-12-10;结束日期:2019-12-10
获取昨天日期范围:
开始日期:2019-12-09;结束日期:2019-12-09
获取下一周日期范围:
开始日期:2019-12-10;结束日期:2019-12-16
获取下一个月日期范围:
开始日期:2019-12-10;结束日期:2020-01-09
*/
复制代码
013.字符替换(时间格式)
/*
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat('2019-12-13', '-', '/')); // 2019/12/13
console.log(transFormat('2019-12-13', '-', '')); // 20191213
复制代码
014.时间补零
如果获取的时间是一位数,则补一个0
Appendzero = obj => {
if (obj < 10 && obj.length < 2) return "0" + obj;
else return obj;
}
复制代码
015.获取当前时间半小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
有可能我们在使用时间数据时,需要使用到的时间必须是两位数,这时候,我们只需要使用上面的时间补零方法,就可以完美的解决了,如下:
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = Appendzero(date.getHours())
let mm = Appendzero(date.getMinutes())
let ss = Appendzero(date.getSeconds())
return hh + ':' + mm + ':' + ss
}
function Appendzero(obj) {
if (obj < 10) return "0" + obj;
else return obj;
}
复制代码
下面紧接着的这两种方法类似!!!
016.获取当前时间1小时之前时间
getOneHour = () => {
let date = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
017.获取当前时间12小时之前时间
getHalfHour = () => {
let date = new Date(new Date().getTime() - 30 * 60 * 1000);
let hh = date.getHours()
let mm = date.getMinutes()
let ss = date.getSeconds()
return hh + ':' + mm + ':' + ss
}
复制代码
018.数字前补零
/*
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
019.UTC转换标准时间
utcToNorm = utcTime => {
// 转为正常的时间格式 年-月-日 时:分:秒
let T_pos = utcTime.indexOf('T');
let Z_pos = utcTime.indexOf('Z');
let year_month_day = utcTime.substr(0, T_pos);
let hour_minute_second = utcTime.substr(T_pos + 1, Z_pos - T_pos - 1);
let newTime = year_month_day + " " + hour_minute_second;
// 处理成为时间戳
timeStamp = new Date(Date.parse(newTime));
timeStamp = timeStamp.getTime();
timeStamp = timeStamp / 1000;
// 增加8个小时,北京时间比utc时间多八个时区
timeStamp = timeStamp + 8 * 60 * 60;
// 时间戳转为时间
let normTime = new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
return normTime;
}
// 测试数据
let date = '2019-12-29T03:14:32.860Z'
// let date = JSON.stringify(new Date())
console.log(utcToNorm(date)); // 2019-12-29 11:14:32
复制代码
020.计算两个日期之间间隔几天
/**
* strDateStart 开始时间 (String)
* strDateEnd 结束时间 (String)
*/
intervalDate = (strDateStart,strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1= strDateStart.split(strSeparator);
oDate2= strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
return iDays ;
}
// 测试数据
console.log(intervalDate('2020-1-3','2019-12-28')); // 6
console.log(intervalDate('2020-01-03','2019-12-25')); // 9
复制代码
021.计算两个日期间隔几天(通过时间戳计算)
/**
* startTime 开始时间 (时间戳-毫秒)
* endTime 结束时间 (时间戳-毫秒)
*/
intervalTimeStamp = (startTime,endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay=Math.floor(intervalTime/(24*3600*1000));
let interval = intervalDay;
return interval;
}
// 测试数据
console.log(intervalTimeStamp(1577808000000,1577980800000)); // 2
复制代码
022.标准时间转时间戳
let date = new Date('2020-03-12 18:00:00');
// 有三种方式转化
let time1 = date.getTime();
let time2 = date.valueOf();
let time3 = Date.parse(date);
console.log(time1); // 1584007200000
console.log(time2); // 1584007200000
console.log(time3); // 1584007200000