1.Date基础方法
//Date基础方法
var time = new Date()
// 返回当日的日期和时间
console.log(time)
//getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31)
time.getDate()
//getDay() 从 Date 对象返回一周中的某一天 (0 ~ 6) 周日 == 0
time.getDay()
//getMonth() 从 Date 对象返回月份 (0 ~ 11)
time.getMonth()
//getFullYear() 从 Date 对象以四位数字返回年份
time.getFullYear()
// getHours() 返回 Date 对象的小时 (0 ~ 23)
time.getHours()
// getMinutes() 返回 Date 对象的分钟 (0 ~ 59)
time.getMinutes()
// getSeconds() 返回 Date 对象的秒数 (0 ~ 59)
time.getSeconds()
// getMilliseconds() 返回 Date 对象的毫秒(0 ~ 999)
time.getMilliseconds()
// getTime() 返回 1970 年 1 月 1 日至今的毫秒数。
time.getTime()
注意:ios内的时间格式不支持"-",需要改成"/",例如:把“2020-03-05”改成:“2020/03/05”,不然使用日期的方法会显示NaN
2.中国标准时间转换YYYY-MM-DD 00:00:00形式
function dealdate(dealdate) {
const date = new Date(dealdate)
const year = date.getFullYear()
let month = date.getMonth() + 1
month = month < 10 ? "0" + month : month
let day = date.getDate()
day = day < 10 ? "0" + day : day
let hour = date.getHours()
hour = hour < 10 ? "0" + hour : hour
let minute = date.getMinutes()
minute = minute < 10 ? "0" + minute : minute
let second = date.getSeconds()
second = second < 10 ? "0" + second : second
return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
}
console.log(dealdate(time))
3.获取最近的日期,前3天,后5天等
function getLatelyDate(fewDays = 1) {
// 当前日期时间
const nowDate = new Date();
return new Date(nowDate.setDate(nowDate.getDate() + fewDays));
}
console.log('今天 :>> ', getLatelyDate(0));
console.log('昨天 :>> ', getLatelyDate(-1));
console.log('明天 :>> ', getLatelyDate(1));
console.log('前30天 :>> ', getLatelyDate(-30));
console.log('后15天 :>> ', getLatelyDate(+15));
4.获取前几月、后几月日期
const getLatelyMonth = (fewMonth = 1) => {
// 当前日期时间
const nowDate = new Date();
// 返回生成的日期
return new Date(nowDate.setMonth(nowDate.getMonth() + fewMonth)).toISOString();
};
console.log('这个月 :>> ', getLatelyMonth(0));
console.log('上个月 :>> ', getLatelyMonth(-1));
console.log('下个月 :>> ', getLatelyMonth(1));
console.log('前10个月 :>> ', getLatelyMonth(-10));
console.log('后10个月 :>> ', getLatelyMonth(+10));
5.时间戳转换为标准时间
//时间戳转换为标准时间
/**
* 参数一 : 时间戳 timestamp: 1659252290626
* 参数二 : 需要转换的格式 yyyy/MM/dd hh:mm:ss
* 返回值 : 根据格式生成的时间
*/
const formatTime = (timestamp, fmtString) => {
// 1. 获取时间对象
const data = new Date(timestamp); // Wed Aug 24 2022 14:44:36 GMT+0800 (中国标准时间)
// 2. 时间转换
const dataO = {
// 匹配 yyyy => 年份
'y+': data.getFullYear(),
// 匹配 MM => 月份
'M+': data.getMonth() + 1,
// 匹配 dd => 日
'd+': data.getDate(),
// 匹配 hh => 时
'h+': data.getHours(),
// 匹配 mm => 分
'm+': data.getMinutes(),
// 匹配 ss => 秒
's+': data.getSeconds()
};
for (const key in dataO) {
// 拿到对应的正则字符串
const timeRegex = new RegExp(key, 'g');
// 看是否需要匹配
if (timeRegex.test(fmtString)) {
// 小于两位数的,用 0 在前方补齐
const value = ('' + dataO[key]).padStart(2, '0');
// 把匹配到的位置用数值来替换
fmtString = fmtString.replace(timeRegex, value);
}
}
return fmtString;
};
//使用方式
// 1. 获取当前时间戳
const nowDate = new Date().getTime();
// 2. 设置格式
// 格式一 => yyyy-MM-dd hh:mm:ss
const fmt1 = 'yyyy-MM-dd hh:mm:ss';
console.log(`格式一 ${fmt1} => `, formatTime(nowDate, fmt1)); // 2023-03-14 14:13:35
// 格式二 => yyyy/MM/dd hh-mm-ss
const fmt2 = 'yyyy/MM/dd hh-mm-ss';
console.log(`格式二 ${fmt2} => `, formatTime(nowDate, fmt2)); // 2023/03/14 14-13-35
// 格式三 => yyyy MM dd hh:mm:ss
const fmt3 = 'yyyy MM dd hh:mm:ss';
console.log(`格式三 ${fmt3} => `, formatTime(nowDate, fmt3)); // 2023 03 14 14:13:35
// 格式四 => hh:mm:ss yyyy-MM-dd
const fmt4 = 'hh:mm:ss yyyy-MM-dd';
console.log(`格式四 ${fmt4} => `, formatTime(nowDate, fmt4)); // 14:13:35 2023-03-14
6.返回指定长度的月份集合
/**
* 返回指定长度的月份集合
*
* @param {time} 时间
* @param {len} 长度
* @param {direction} 方向: 1: 前几个月; 2: 后几个月; 3:前后几个月 默认 3
* @return {Array} 数组
*
* @example getMonths('2018-1-29', 6, 1) // -> ["2018-1", "2017-12", "2017-11", "2017-10", "2017-9", "2017-8", "2017-7"]
*/
function getMonths(time, len, direction) {
var mm = new Date(time).getMonth(),
yy = new Date(time).getFullYear(),
direction = isNaN(direction) ? 3 : direction,
index = mm;
var cutMonth = function(index) {
if ( index <= len && index >= -len) {
return direction === 1 ? formatPre(index).concat(cutMonth(++index)):
direction === 2 ? formatNext(index).concat(cutMonth(++index)):formatCurr(index).concat(cutMonth(++index))
}
return []
}
var formatNext = function(i) {
var y = Math.floor(i/12),
m = i%12
return [yy+y + '-' + (m+1)]
}
var formatPre = function(i) {
var y = Math.ceil(i/12),
m = i%12
m = m===0 ? 12 : m
return [yy-y + '-' + (13 - m)]
}
var formatCurr = function(i) {
var y = Math.floor(i/12),
yNext = Math.ceil(i/12),
m = i%12,
mNext = m===0 ? 12 : m
return [yy-yNext + '-' + (13 - mNext),yy+y + '-' + (m+1)]
}
// 数组去重
var unique = function(arr) {
if ( Array.hasOwnProperty('from') ) {
return Array.from(new Set(arr));
}else{
var n = {},r=[];
for(var i = 0; i < arr.length; i++){
if (!n[arr[i]]){
n[arr[i]] = true;
r.push(arr[i]);
}
}
return r;
}
}
return direction !== 3 ? cutMonth(index) : unique(cutMonth(index).sort(function(t1, t2){
return new Date(t1).getTime() - new Date(t2).getTime()
}))
}
7.返回指定长度的天数集合
/**
* 返回指定长度的天数集合
*
* @param {time} 时间
* @param {len} 长度
* @param {direction} 方向: 1: 前几天; 2: 后几天; 3:前后几天 默认 3
* @return {Array} 数组
*
* @example date.getDays('2018-1-29', 6) // -> ["2018-1-26", "2018-1-27", "2018-1-28", "2018-1-29", "2018-1-30", "2018-1-31", "2018-2-1"]
*/
function getDays(time, len, diretion) {
var tt = new Date(time)
var getDay = function (day) {
var t = new Date(time)
t.setDate(t.getDate() + day)
var m = t.getMonth() + 1
return t.getFullYear() + '-' + m + '-' + t.getDate()
}
var arr = []
if (diretion === 1) {
for (var i = 1; i <= len; i++) {
arr.unshift(getDay(-i))
}
} else if (diretion === 2) {
for (var i = 1; i <= len; i++) {
arr.push(getDay(i))
}
} else {
for (var i = 1; i <= len; i++) {
arr.unshift(getDay(-i))
}
arr.push(tt.getFullYear() + '-' + (tt.getMonth() + 1) + '-' + tt.getDate())
for (var i = 1; i <= len; i++) {
arr.push(getDay(i))
}
}
return diretion === 1 ? arr.concat([tt.getFullYear() + '-' + (tt.getMonth() + 1) + '-' + tt.getDate()]) :
diretion === 2 ? [tt.getFullYear() + '-' + (tt.getMonth() + 1) + '-' + tt.getDate()].concat(arr) : arr
}