这篇文章主要介绍了js获取今天、昨天、明天的日期函数代码,需要的朋友可以参考下
今天发现的一个比较好的函数
/*
* @params date 日期
* @params type 日期 prev/current/next 昨天/今天/明天
* @params fmt 日期拼接符
*/
function getDays(date, type, fmt) {
let currentDate = new Date(date)
let y = currentDate.getFullYear()
let m = currentDate.getMonth() + 1
let d = currentDate.getDate()
function dateFormat(date, fmt) {
let y = new Date(date).getFullYear()
let m = new Date(date).getMonth() + 1
let d = new Date(date).getDate()
return `${y}${fmt}${m}${fmt}${d}`
}
switch (type) {
case "prev":
if (d - 1 < 1) {
if (m - 1 < 1) {
y = y - 1
m = 12
} else {
m = m - 1
}
d = new Date(y, m, 0).getDate()
} else {
d = d - 1
}
break
case "current":
break
case "next":
if (d + 1 > new Date(y, m, 0).getDate()) {
if (m + 1 > 12) {
y = y + 1
m = 1
d = 1
} else {
m = m + 1
d = 1
}
} else {
d = d + 1
}
break;
default:
break;
}
return dateFormat(new Date(`${y}-${m}-${d}`), fmt)
}
console.log(getDays(new Date('2023-5-13'), "prev", "-"));
console.log(getDays(new Date('2023-5-30'), "next", "-"));
console.log(getDays(new Date('2023-5-31'), "next", "-"));
再补充一个js 日期 获取今天、昨天、明天的函数
function getDay(day){
var today = new Date()
// 获取时间戳(毫秒级)
/*
day为1,则是,明天的时间戳
day为-1,则是,昨天的时间戳
day为-2,则是,前天的时间戳
*/
var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
// Date.setTime(时间戳):设置当前日期的时间
today.setTime(targetday_milliseconds)
console.log('today=', today) // today= Sun Mar 05 2023 16:14:56 GMT+0800 (中国标准时间)
var tYear = today.getFullYear() // 年
var tMonth = today.getMonth() // 月
var tDate = today.getDate() // 日
tMonth = this.doHandleMonth(tMonth + 1)
tDate = this.doHandleMonth(tDate)
console.log('返回年月日=', tYear + '-' + tMonth + '-' + tDate)
return tYear + '-' + tMonth + '-' + tDate
}
function doHandleMonth(month) {
var m = month
if (month.toString().length == 1) {
m = '0' + month
}
return m
}
到此这篇关于js获取今天、昨天、明天的日期函数代码的文章就介绍到这了,更多相关js获取明天的日期内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:js获取今天、昨天、明天的日期函数代码


猜你喜欢
- javascript 判断当前浏览器版本并判断ie版本 2023-08-08
- 基于CORS实现WebApi Ajax 跨域请求解决方法 2023-02-14
- 1 Vue - 简介 2023-10-08
- jsPlumb+vue创建字段映射关系 2023-10-08
- layui数据表格以及传数据方式 2022-12-13
- vue keep-alive 2023-10-08
- JS实现左侧菜单工具栏 2022-08-31
- 深入浅析AjaxFileUpload实现单个文件的 Ajax 文件上传库 2022-12-15
- 关于 html:如何从 css 表中删除边距和填充 2022-09-21
- ajax实现输入提示效果 2023-02-14