当前位置:网站首页>js 格式化当前时间 日期推算
js 格式化当前时间 日期推算
2022-04-23 06:01:00 【NOyesNONO_】
//第一位表示距离今天还有几天,如0表示今天,1表示明天,-1表示昨天
//第二位表示指定日期,默认不传为今天,支持格式'2020-10-10', '2020/01/01'
function getTargetDate(num = 0, baseDate = null) {
let tarDate = ''//目标日期
if (baseDate) {
tarDate = new Date(baseDate);
} else {
tarDate = new Date();
}
//如果num不为0 说明要推移时间,需要把基础时间转换成时间戳的形式进行计算
if (num !== 0) {
tarDate = tarDate.getFullYear() + '-' + (tarDate.getMonth() + 1) + '-' + tarDate.getDate() + ' 00:00:00';// Year-Month-Date 00:00:00
tarDate = Date.parse(tarDate.replace(/-/g, '/'));//把指定时间转换为时间戳,ie不支持‘/’,Date.parse(Year-Month-Date)
tarDate += (86400000) * num;//修改后的时间戳,24*60*60 = 86400000 一天的毫秒数
tarDate = new Date(tarDate);//时间戳转换为时间
// tarDate = new Date(tarDate.setDate(tarDate.getDate() + num))//todo 这一行代替上边四行
}
//把new Date()的形式 格式化
const weekday = [
"周日",
"周一",
"周二",
"周三",
"周四",
"周五",
"周六",
];
const y = tarDate.getFullYear();
let month = (tarDate.getMonth() + 1);
month = month < 10 ? "0" + month : month
let date = tarDate.getDate(); //直接date上加减遇见跨月的会有问题,getDate后得到一个数字,01-2 = -1
date = date < 10 ? "0" + date : date
const d = weekday[tarDate.getDay()];
let h;
h = tarDate.getHours() < 10 ? "0" + tarDate.getHours() : tarDate.getHours()
let m;
m = tarDate.getMinutes() < 10 ? "0" + tarDate.getMinutes() : tarDate.getMinutes()
let s;
s = tarDate.getSeconds() < 10 ? "0" + tarDate.getSeconds() : tarDate.getSeconds()
let resDate = `${
y}-${
month}-${
date}`
let resNumDate = '' + y + month + date
let currentTime = `${
h}:${
m}:${
s}`
return {
year: y,
month: month,
date: date,
weekday: d,
hour: h,
minute: m,
second: s,
resDate: resDate,//Year-Month-Date
resNumDate: resNumDate,//YearMonthDte
currentTime: currentTime,//xx:xx:xx
}
}
//支持的入参
getTargetDate().currentTime // 16:05:05
getTargetDate().resNumDate //20201212 当天
getTargetDate().resDate//2020-12-12 当天
getTargetDate(-1).resDate//2020-12-11 一天前
getTargetDate().weekday //周六
getTargetDate(2,'2022-01-18').resDate //2022-01-20,指定2022-01-18的两天后
版权声明
本文为[NOyesNONO_]所创,转载请带上原文链接,感谢
https://blog.csdn.net/NOyesNONO_/article/details/122683550
边栏推荐
猜你喜欢
随机推荐
异常记录-5
JS performance optimization
file_ get_ Two solutions to content accessing SSL errors
SQL学习|窗口函数
ebfp编程常用API介绍
如何通过dba_hist_active_sess_history分析数据库历史性能问题
Ansible basic commands, roles, built-in variables and tests judgment
[ES6 quick start]
rdma网络介绍
修改Jupyter Notebook样式
关于Postgres主从复制延迟监控的错误告警问题
通过源码探究@ModelAndView如何实现数据与页面的转发
异常记录-8
tc ebpf 实践
Typescript (top)
Virtio and Vhost_ Net introduction
阅读笔记:Secure Federated Matrix Factorization
JS implementation of web page rotation map
rdma 编程详解
[shell script exercise] batch add the newly added disks to the specified VG









