moment常用时间封装(几天前,几周前,几月前,几年前)
·
封装时间API
自己封装了项目中需要用的常用时间,比如当前时间,几天前,几周前等等。一些UI组件比如antd,element等需要用moment对象的日期、时间组件可以直接用。
上代码。
import moment from 'moment'
/**
* 获取当前时间
* @returns {moment.Moment}
*/
export const getNowDate = () => {
return moment(new Date(), 'YYYY-MM-DD')
}
/**
* 当前时间之前的几天
* @param number
* @returns {moment.Moment}
*/
export const getPreDayDate = (number) => {
const curTime = new Date().getTime()
const date2 = curTime - number * 3600 * 24 * 1000
const nDate = new Date(date2)
return moment(nDate)
}
/**
* 当前时间之前的一个月
* @returns {moment.Moment}
*/
export const getBeforeDate = () => {
const date = new Date()
let time = date.getTime()
time -= 30 * 86400000
const nDate = new Date(time)
return moment(nDate.toLocaleDateString())
}
/**
* 当前时间之前的几周
* @param number
* @returns {*|moment.Moment}
*/
export const getPreWeekDate = (number) => {
const nowDate = new Date().getTime()
const date2 = nowDate - number * 7 * 24 * 60 * 60 * 1000
const nDate = new Date(date2)
return moment(nDate)
}
/**
* 当前时间之前的几年
* @param number
* @returns {*|moment.Moment}
*/
export const getBeforeYearDate = (number) => {
const date = new Date()
date.setFullYear(date.getFullYear() - number)
return moment(new Date(date))
}
/**
* 获取指定时间那天的 00:00:00开始的时间
* @param data
* @returns {string}
*/
export const getStartDate = (data) => {
if (!data) {
return ''
}
return data.format('YYYY-MM-DD') + ' 00:00:00'
}
/**
* 获取指定时间的 23:59:59结束的时间
* @param data
* @returns {string}
*/
export const getEndDate = (data) => {
if (!data) {
return ''
}
return data.format('YYYY-MM-DD') + ' 23:59:59'
}
/**
* 格式化时间
* @param data
* @param format
*/
export const formatDate = (data, format) => {
if (!data) {
return ''
}
return data.format(format)
}
📦 前端资源合集 | 持续更新
🟢 前端0到1【持续更新】→ https://pan.quark.cn/s/5df55ccff7c4
🔵 前端进阶【持续更新】→ https://pan.quark.cn/s/2dec1c87b3ec
🟣 前端2026最新【持续更新】→ https://pan.quark.cn/s/77c8fa94161c
🔴 AI最新学习资料 → https://pan.baidu.com/s/1P9X2Qk_Fby3rFNVGw_WKow?pwd=46XG 提取码:46XG
觉得有用就点个赞+收藏,关注我持续分享前端干货 💡
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)