js 操作在当前日期加减(天、周、月、年数)
前几天一个月薪35k的兄弟,给我推了一个人工智能学习网站,看了一段时间挺有意思的。包括语音识别、机器翻译等从基础到实战都有,很详细,分享给大家。大家及时保存,说不定啥时候就没了。
封装
utils.js
// 时间戳转时间,精确到日
export function timestampToTime (timestamp) {
var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
var Y = date.getFullYear() + '-';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
return Y + M + D;
}
/**
* 返回最近几天的函数
* @param {*}
* dayNum 返回最近dayNum的日期和当前日期
* @returns
*/
export function getNextDay (dayNum) {
let nowDate = new Date()
// 这里可以减可以加
let newDate = nowDate.setDate(nowDate.getDate() - dayNum)
return {
startTime: timestampToTime(newDate),
endTime: timestampToTime(new Date())
}
}
使用
import { getNextDay } from '../../utils.js'
getNextDay (5)
其他
// 时间戳转时间,获取月日
export function timestampToTime () {
const date = new Date()
// const Y = date.getFullYear() + '-'
const M = (date.getMonth() + 1) + '月'
const D = date.getDate() + '日'
return M + D
}
// 获取星期几
export function getWeek () {
let weeks = ['日', '一', '二', '三', '四', '五', '六'];
let day = new Date().getDay();
console.log(day);
return `星期${weeks[day]}`
}