常用的日期格式获取、转换
获取本周、本月、本年的起止时间范围
import dayjs from 'dayjs'
import type { Dayjs } from 'dayjs'
type TimeFlag = 'ymd' | 'ym' | 'ymdt'
export type RangeValue = [Dayjs, Dayjs]
export type RangeStamp = [number, number]
export function formatTime(time: string | number, flag: TimeFlag): string {
const timeObj = {
ymd: 'YYYY-MM-DD',
ym: 'YYYY-MM',
ymdt: 'YYYY-MM-DD HH:mm:ss'
}
const date = dayjs(+time).format(timeObj[flag])
console.log('🚀 ~ file: dateUtil.ts ~ line 13 ~ date', date)
return date
}
export function getTheWeek(): RangeStamp {
// 当天 0 点的时间戳
const dateStamp = new Date(new Date().toLocaleDateString()).getTime()
const weekStart = new Date(
dateStamp - 3600 * 1000 * 24 * (new Date().getDay() - 1)
)
const weekEnd = new Date(
dateStamp + 3600 * 1000 * 24 * (7 + 1 - new Date().getDay())
)
console.log(
'🚀 ~ file: dateUtil.ts ~ line 46 ~ getTheWeek ~ weekStart',
weekStart,
weekStart.getTime()
)
console.log(
'🚀 ~ file: dateUtil.ts ~ line 53 ~ getTheWeek ~ weekEnd',
weekEnd,
weekEnd.getTime()
)
const start_time = dayjs().startOf('week').format('YYYY-MM-DD HH:mm:ss')
const end_time = dayjs().endOf('week').format('YYYY-MM-DD HH:mm:ss')
console.log(
'🚀 ~ file: dateUtil.ts ~ line 40 ~ getTheWeek ~ start_time',
start_time,
dayjs(start_time).valueOf()
)
console.log(
'🚀 ~ file: dateUtil.ts ~ line 42 ~ getTheWeek ~ end_time',
end_time,
dayjs(end_time).valueOf()
)
const startStamp = dayjs(start_time).valueOf()
const endStamp = dayjs(end_time).valueOf()
return [startStamp, endStamp]
}
export function getTheMonth(): RangeStamp {
const date = new Date()
const monthStart = new Date(date.getFullYear(), date.getMonth(), 1) // 本月第一天
const monthEnd = new Date(date.getFullYear(), date.getMonth() + 1, 1) // 本月的最后一天(取下月1号0点)
console.log(
'🚀 ~ file: dateUtil.ts ~ line 61 ~ getTheMonth ~ monthStart',
monthStart,
monthStart.getTime()
)
console.log(
'🚀 ~ file: dateUtil.ts ~ line 71 ~ getTheMonth ~ monthEnd',
monthEnd,
monthEnd.getTime()
)
const start_time = dayjs().startOf('month').format('YYYY-MM-DD HH:mm:ss')
const end_time = dayjs().endOf('month').format('YYYY-MM-DD HH:mm:ss')
console.log(
'🚀 ~ file: dateUtil.ts ~ line 69 ~ getTheMonth ~ start_time',
start_time,
dayjs(start_time).valueOf()
)
console.log(
'🚀 ~ file: dateUtil.ts ~ line 71 ~ getTheMonth ~ end_time',
end_time,
dayjs(end_time).valueOf()
)
const startStamp = dayjs(start_time).valueOf()
const endStamp = dayjs(end_time).valueOf()
return [startStamp, endStamp]
}
export function getTheYear(): RangeStamp {
const date = new Date()
const startTime = new Date(date.getFullYear(), 0, 1) // 本月第一天
const endTime = new Date(date.getFullYear() + 1, 0, 1) // 本月的最后一天(取下月1号0点)
console.log(
'🚀 ~ file: dateUtil.ts ~ line 81 ~ getTheYear ~ start_time',
startTime,
startTime.getTime()
)
console.log(
'🚀 ~ file: dateUtil.ts ~ line 91 ~ getTheYear ~ end_time',
endTime,
endTime.getTime()
)
const start_time = dayjs().startOf('year').format('YYYY-MM-DD HH:mm:ss')
const end_time = dayjs().endOf('year').format('YYYY-MM-DD HH:mm:ss')
console.log(
'🚀 ~ file: dateUtil.ts ~ line 99 ~ getTheYear ~ start_time',
start_time,
dayjs(start_time).valueOf()
)
console.log(
'🚀 ~ file: dateUtil.ts ~ line 107 ~ getTheYear ~ end_time',
end_time,
dayjs(end_time).valueOf()
)
const startStamp = dayjs(start_time).valueOf()
const endStamp = dayjs(end_time).valueOf()
return [startStamp, endStamp]
}
时间戳转换成格式化日期
/*
* @Author: hhn
* @Date: 2020-07-05 16:57:46
* @lastEditTime: Do not edit
* @Description: timestamp缺省表示使用当前时间戳,formats默认格式是Y-m-d,例如2018-01-01。
* @FilePath: \codehub\study\studying\javascript\test.js
*/
var dateFormat = function(timestamp, formats) {
// formats格式包括
// 1. Y-m-d
// 2. Y-m-d H:i:s
// 3. Y年m月d日
// 4. Y年m月d日 H时i分
formats = formats || 'Y-m-d';
var zero = function(value) {
if (value < 10) {
return '0' + value;
}
return value;
};
var myDate = timestamp ? new Date(timestamp) : new Date();
var year = myDate.getFullYear();
var month = zero(myDate.getMonth() + 1);
var day = zero(myDate.getDate());
var hour = zero(myDate.getHours());
var minite = zero(myDate.getMinutes());
var second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function(matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
let date = new Date()
console.log("date", date)
console.log("dateFormat(date)", dateFormat(date))
时间戳转化为显示为多少分钟前,多少天前的处理
/*
** 时间戳显示为多少分钟前,多少天前的处理
** eg.
** console.log(dateDiff(1411111111111)); // 2014年09月19日
** console.log(dateDiff(1481111111111)); // 9月前
** console.log(dateDiff(1499911111111)); // 2月前
** console.log(dateDiff(1503211111111)); // 3周前
** console.log(dateDiff(1505283100802)); // 1分钟前
*/
var dateDiff = function(timestamp) {
// 补全为13位
var arrTimestamp = (timestamp + '').split('');
for (var start = 0; start < 13; start++) {
if (!arrTimestamp[start]) {
arrTimestamp[start] = '0';
}
}
timestamp = arrTimestamp.join('') * 1;
var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var halfamonth = day * 15;
var month = day * 30;
var now = new Date().getTime();
var diffValue = now - timestamp;
// 如果本地时间反而小于变量时间
if (diffValue < 0) {
return '不久前';
}
// 计算差异时间的量级
var monthC = diffValue / month;
var weekC = diffValue / (7 * day);
var dayC = diffValue / day;
var hourC = diffValue / hour;
var minC = diffValue / minute;
// 数值补0方法
var zero = function(value) {
if (value < 10) {
return '0' + value;
}
return value;
};
// 使用
if (monthC > 12) {
// 超过1年,直接显示年月日
return (function() {
var date = new Date(timestamp);
return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
})();
} else if (monthC >= 1) {
return parseInt(monthC) + "月前";
} else if (weekC >= 1) {
return parseInt(weekC) + "周前";
} else if (dayC >= 1) {
return parseInt(dayC) + "天前";
} else if (hourC >= 1) {
return parseInt(hourC) + "小时前";
} else if (minC >= 1) {
return parseInt(minC) + "分钟前";
}
return '刚刚';
};
console.log("dateDiff()", dateDiff())
微信小程序版
const formatMsgTime = function (dateStr) {
var dateObj = dateStr.replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '').replace(/(-)/g, '/')
var targetDate = new Date(dateObj);
var year = targetDate.getFullYear();
var month = targetDate.getMonth() + 1;
var day = targetDate.getDate();
var hour = targetDate.getHours();
var minute = targetDate.getMinutes();
var second = targetDate.getSeconds();
var nowDate = new Date();
var now_new = Date.parse(nowDate.toString());
var milliseconds = 0;
var timeSpanStr;
milliseconds = now_new - targetDate;
if (milliseconds <= 1000 * 60 * 1) {
timeSpanStr = '刚刚';
}
else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
}
else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
}
else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
}
else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == nowDate.getFullYear()) {
timeSpanStr = month + '-' + day;
} else {
timeSpanStr = year + '-' + month + '-' + day;
}
return timeSpanStr;
}
module.exports = {
formatMsgTime: formatMsgTime
}
使用方法
1,将上述代码保存为utils-days.js文件,放置在小程序公用目录里;
2,在需要使用的页面或者模块的js文件头部,导入该文件;
3,const utilsDays = require(‘../utils/utils-days’);
4, 使用该方法;
示例代码
this.setData({
newDate: utilsDays.formatMsgTime(systemDate);
})
获取当前日期的星期数 本年度第几周
function getWeekNumber(date) {
// date 'yyyy-MM-dd'
date = new Date(date);
var date2 = new Date(date.getFullYear(), 0, 1);
var day1 = date.getDay();
if (day1 == 0) day1 = 7;
var day2 = date2.getDay();
if (day2 == 0) day2 = 7;
let d = Math.round((date.getTime() - date2.getTime() + (day2 - day1) * (24 * 60 * 60 * 1000)) / 86400000);
var getFullYear = date.getFullYear();
var getWeekNo = (Math.ceil(d / 7) + 1);
getWeekNo = (getWeekNo > 9 ? "" : "0") + getWeekNo;
//当周数大于52
if ((Math.ceil(d / 7) + 1) > 52) {
if (date.getMonth() == 11) {
// 还在当年12月份,则为当年第53周
return [getFullYear, "53"]
}
// 已经跨年,为下一年的第一周
return [getFullYear + 1, "01"]
}
return [getFullYear, getWeekNo];
}
JS 获取某月的天数
一三五七八十腊,31天永不差,四六九十一,每月30天,惟有二月二十八,闰年要把日加一。
这里面还有个闰年的计算规则:四年一闰,百年不闰,四百年再闰。可以被4整除,但是不能被100整除,除非可以被400整除。
function getMonthCountDay(year, month){
// year 为年份,month 为月份
}
[[2000,2],[2000,1],[2000,3],[2000,4],[2100,2],[2100,1],[2100,3],[2100,4],[2104,2],[2104,1],[2104,3],[2104,4],[2105,2],[2105,1],[2105,3],[2105,4],].map(v=>`${v} => ${getMonthCountDay.apply(null,v)}天`)
switch方案
function getMonthCountDay (year, month) {
switch (month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31
case 4:
case 6:
case 9:
case 11:
return 30
case 2:
return year%400==0?(29):(year%4!=0||year%100==0?28:29)
}
}
Date
API 处理日期溢出特性(进位)
function getMonthCountDay (year, month) {
return 32 - new Date(year, month-1, 32).getDate()
}
Date
API 处理日期溢出特性(退位方案)
function getMonthCountDay (year, month) {
return new Date(year, month, 0).getDate()
}