datetimeUtils
大约 11 分钟javascript
使用方法
下面的源码文件 datetimeUtils.js 使用了 立即执行函数表达式 将 DatetimeUtils 暴露给全局作用域,在 a.html 的 header 中导入 datetimeUtils.js,在 a.html 的 body 末尾导入 a.js,之后 a.js 就可以直接使用函数 DatetimeUtils.isLeapYear(xxx) ,不需要在 a.js 中声明 const DatetimeUtils = new DatetimeUtils()
源码
JS验证过
/**
* 日期处理工具类
*/
var DatetimeUtils = function(){
/**
* 判断闰年
* @param date Date日期对象
* @return boolean true 或false
*/
this.isLeapYear = function(date){
return (0==date.getYear()%4&&((date.getYear()%100!=0)||(date.getYear()%400==0)));
}
/**
* 日期对象转换为指定格式的字符串
* @param f 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
* @param date Date日期对象, 如果缺省,则为当前时间
*
* YYYY/yyyy/YY/yy 表示年份
* MM/M 月份
* W/w 星期
* dd/DD/d/D 日期
* hh/HH/h/H 时间
* mm/m 分钟
* ss/SS/s/S 秒
* @return string 指定格式的时间字符串
*/
this.dateToStr = function(formatStr, date){
formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
date = arguments[1] || new Date();
var str = formatStr;
var Week = ['日','一','二','三','四','五','六'];
str=str.replace(/yyyy|YYYY/,date.getFullYear());
str=str.replace(/yy|YY/,(date.getYear() % 100)>9?(date.getYear() % 100).toString():'0' + (date.getYear() % 100));
str=str.replace(/MM/,date.getMonth()>9?(date.getMonth() + 1):'0' + (date.getMonth() + 1));
str=str.replace(/M/g,date.getMonth());
str=str.replace(/w|W/g,Week[date.getDay()]);
str=str.replace(/dd|DD/,date.getDate()>9?date.getDate().toString():'0' + date.getDate());
str=str.replace(/d|D/g,date.getDate());
str=str.replace(/hh|HH/,date.getHours()>9?date.getHours().toString():'0' + date.getHours());
str=str.replace(/h|H/g,date.getHours());
str=str.replace(/mm/,date.getMinutes()>9?date.getMinutes().toString():'0' + date.getMinutes());
str=str.replace(/m/g,date.getMinutes());
str=str.replace(/ss|SS/,date.getSeconds()>9?date.getSeconds().toString():'0' + date.getSeconds());
str=str.replace(/s|S/g,date.getSeconds());
return str;
}
/**
* 日期计算
* @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
* @param num int
* @param date Date 日期对象
* @return Date 返回日期对象
*/
this.dateAdd = function(strInterval, num, date){
date = arguments[2] || new Date();
switch (strInterval) {
case 's' :return new Date(date.getTime() + (1000 * num));
case 'n' :return new Date(date.getTime() + (60000 * num));
case 'h' :return new Date(date.getTime() + (3600000 * num));
case 'd' :return new Date(date.getTime() + (86400000 * num));
case 'w' :return new Date(date.getTime() + ((86400000 * 7) * num));
case 'm' :return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
case 'y' :return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
}
}
/**
* 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串
* @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
* @param dtStart Date 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
* @param dtEnd Date 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
*/
this.dateDiff = function(strInterval, dtStart, dtEnd) {
switch (strInterval) {
case 's' :return parseInt((dtEnd - dtStart) / 1000);
case 'n' :return parseInt((dtEnd - dtStart) / 60000);
case 'h' :return parseInt((dtEnd - dtStart) / 3600000);
case 'd' :return parseInt((dtEnd - dtStart) / 86400000);
case 'w' :return parseInt((dtEnd - dtStart) / (86400000 * 7));
case 'm' :return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);
case 'y' :return dtEnd.getFullYear() - dtStart.getFullYear();
}
}
/**
* 字符串转换为日期对象
* @param date Date 格式为yyyy-MM-dd HH:mm:ss,必须按年月日时分秒的顺序,中间分隔符不限制
*/
this.strToDate = function(dateStr){
var data = dateStr;
var reCat = /(\d{1,4})/gm;
var t = data.match(reCat);
t[1] = t[1] - 1;
eval('var d = new Date('+t.join(',')+');');
return d;
}
/**
* 把指定格式的字符串转换为日期对象yyyy-MM-dd HH:mm:ss
*
*/
this.strFormatToDate = function(formatStr, dateStr){
var year = 0;
var start = -1;
var len = dateStr.length;
if((start = formatStr.indexOf('yyyy')) > -1 && start < len){
year = dateStr.substr(start, 4);
}
var month = 0;
if((start = formatStr.indexOf('MM')) > -1 && start < len){
month = parseInt(dateStr.substr(start, 2)) - 1;
}
var day = 0;
if((start = formatStr.indexOf('dd')) > -1 && start < len){
day = parseInt(dateStr.substr(start, 2));
}
var hour = 0;
if( ((start = formatStr.indexOf('HH')) > -1 || (start = formatStr.indexOf('hh')) > 1) && start < len){
hour = parseInt(dateStr.substr(start, 2));
}
var minute = 0;
if((start = formatStr.indexOf('mm')) > -1 && start < len){
minute = dateStr.substr(start, 2);
}
var second = 0;
if((start = formatStr.indexOf('ss')) > -1 && start < len){
second = dateStr.substr(start, 2);
}
return new Date(year, month, day, hour, minute, second);
}
/**
* 日期对象转换为毫秒数
*/
this.dateToLong = function(date){
return date.getTime();
}
/**
* 毫秒转换为日期对象
* @param dateVal number 日期的毫秒数
*/
this.longToDate = function(dateVal){
return new Date(dateVal);
}
/**
* 判断字符串是否为日期格式
* @param str string 字符串
* @param formatStr string 日期格式, 如下 yyyy-MM-dd
*/
this.isDate = function(str, formatStr){
if (formatStr == null){
formatStr = "yyyyMMdd";
}
var yIndex = formatStr.indexOf("yyyy");
if(yIndex==-1){
return false;
}
var year = str.substring(yIndex,yIndex+4);
var mIndex = formatStr.indexOf("MM");
if(mIndex==-1){
return false;
}
var month = str.substring(mIndex,mIndex+2);
var dIndex = formatStr.indexOf("dd");
if(dIndex==-1){
return false;
}
var day = str.substring(dIndex,dIndex+2);
if(!isNumber(year)||year>"2100" || year< "1900"){
return false;
}
if(!isNumber(month)||month>"12" || month< "01"){
return false;
}
if(day>getMaxDay(year,month) || day< "01"){
return false;
}
return true;
}
this.getMaxDay = function(year,month) {
if(month==4||month==6||month==9||month==11)
return "30";
if(month==2)
if(year%4==0&&year%100!=0 || year%400==0)
return "29";
else
return "28";
return "31";
}
/**
* 变量是否为数字
*/
this.isNumber = function(str)
{
var regExp = /^\d+$/g;
return regExp.test(str);
}
/**
* 把日期分割成数组 [年、月、日、时、分、秒]
*/
this.toArray = function(myDate)
{
myDate = arguments[0] || new Date();
var myArray = Array();
myArray[0] = myDate.getFullYear();
myArray[1] = myDate.getMonth();
myArray[2] = myDate.getDate();
myArray[3] = myDate.getHours();
myArray[4] = myDate.getMinutes();
myArray[5] = myDate.getSeconds();
return myArray;
}
/**
* 取得日期数据信息
* 参数 interval 表示数据类型
* y 年 M月 d日 w星期 ww周 h时 n分 s秒
*/
this.datePart = function(interval, myDate)
{
myDate = arguments[1] || new Date();
var partStr='';
var Week = ['日','一','二','三','四','五','六'];
switch (interval)
{
case 'y' :partStr = myDate.getFullYear();break;
case 'M' :partStr = myDate.getMonth()+1;break;
case 'd' :partStr = myDate.getDate();break;
case 'w' :partStr = Week[myDate.getDay()];break;
case 'ww' :partStr = myDate.WeekNumOfYear();break;
case 'h' :partStr = myDate.getHours();break;
case 'm' :partStr = myDate.getMinutes();break;
case 's' :partStr = myDate.getSeconds();break;
}
return partStr;
}
/**
* 取得当前日期所在月的最大天数
*/
this.maxDayOfDate = function(date)
{
date = arguments[0] || new Date();
date.setDate(1);
date.setMonth(date.getMonth() + 1);
var time = date.getTime() - 24 * 60 * 60 * 1000;
var newDate = new Date(time);
return newDate.getDate();
}
/**
* 2021年9月16日 11:19:16 chanchaw
* 传入一个日期返回该日期所在月份的最大天数
*/
this.getMonthMaxDay = function(date)
{
date = arguments[0] || new Date();
// 传入的是字符串类型的日期则转换为日期类型对象
if( typeof(date) == 'string' )
date = strToDate(date)
date.setDate(1);
date.setMonth(date.getMonth() + 1);
var time = date.getTime() - 24 * 60 * 60 * 1000;
var newDate = new Date(time);
return newDate.getDate();
}
/**
* 2021年9月16日 11:20:33 chanchaw
* 返回上个月最后一天的日期
*/
this.lastMonthLastDay = function()
{
let firstDay = curMonthFirstDay();// 获取当月的第一天
return dateAdd('d',-1,firstDay);
}
/**
* 2021年9月16日 12:10:44 chanchaw
* 获取当月的第一天,0点0分
*/
this.curMonthFirstDay = function() {
const nowDay = new Date();
let curMonth = nowDay.getMonth() + 1;// 获取当月月份
const firstDay = String(nowDay.getFullYear()) + '-' + String(curMonth.toString()) + '-01';// 获取当月第一天
return strToDate(firstDay);
}
return this;
}();
小程序使用过
const formatDateTimeDo = (date: Date) => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return (
[year, month, day].map(formatNumber).join(DELIMITTER_DATE) +
' ' +
[hour, minute, second].map(formatNumber).join(DELIMITTER_TIME)
)
}
const formatDateTime = (date:Date, format:string):string => {
if(format === undefined || format === null) return formatDateTimeDo(date);
const o = {
"M+": date.getMonth() + 1, // 月份
"d+": date.getDate(), // 日
"h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
"H+": date.getHours(), // 小时
"m+": date.getMinutes(), // 分
"s+": date.getSeconds(), // 秒
"q+": Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds(), // 毫秒
a: date.getHours() < 12 ? "上午" : "下午", // 上午/下午
A: date.getHours() < 12 ? "AM" : "PM", // AM/PM
};
if (/(y+)/.test(format)) {
format = format.replace(
RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length)
);
}
for (let k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(
RegExp.$1,
RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
);
}
}
return format;
}
// 使用案例
console.log('下面是各种格式的日期时间表现形式:');
console.log(dateTimeUtils.formatDateTime(new Date(),'yyyy-MM-dd HH:mm:ss'));//2025-01-14 10:18:43
console.log(dateTimeUtils.formatDateTime(new Date(),'yyyy-MM-dd HH:mm:ss.S'));//2025-01-14 10:18:43.442
console.log(dateTimeUtils.formatDateTime(new Date(),'yyyy-MM-dd'));//2025-01-14
console.log(dateTimeUtils.formatDateTime(new Date(),'HH:mm:ss'));//10:18:43
console.log(dateTimeUtils.formatDateTime(new Date(),'yyyy-MM-dd HH:mm'));//2025-01-14 10:18
console.log(dateTimeUtils.formatDateTime(new Date()));//2025-01-14 10:20:11
console.log('=======================================================================');
module
/**
* 判断闰年
* @param date Date日期对象
* @return boolean true 或false
*/
const isLeapYear = function(date){
return (0==date.getYear()%4&&((date.getYear()%100!=0)||(date.getYear()%400==0)));
}
/**
* 日期对象转换为指定格式的字符串
* @param f 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
* @param date Date日期对象, 如果缺省,则为当前时间
*
* YYYY/yyyy/YY/yy 表示年份
* MM/M 月份
* W/w 星期
* dd/DD/d/D 日期
* hh/HH/h/H 时间
* mm/m 分钟
* ss/SS/s/S 秒
* @return string 指定格式的时间字符串
*/
const dateToStr = function(date = new Date(),formatStr = "yyyy-MM-dd HH:mm:ss") {
let str = formatStr;
const Week = ['日', '一', '二', '三', '四', '五', '六'];
const year = date.getFullYear();
const month = date.getMonth() + 1; // 月份修正为1-12
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const weekday = date.getDay();
// 年替换
str = str.replace(/yyyy|YYYY/g, year);
str = str.replace(/yy|YY/g, (year % 100).toString().padStart(2, '0'));
// 月替换
str = str.replace(/MM/g, month.toString().padStart(2, '0'));
str = str.replace(/M/g, month.toString());
// 周替换
str = str.replace(/w|W/g, Week[weekday]);
// 日替换
str = str.replace(/dd|DD/g, day.toString().padStart(2, '0'));
str = str.replace(/d|D/g, day.toString());
// 小时替换
str = str.replace(/hh|HH/g, hours.toString().padStart(2, '0'));
str = str.replace(/h|H/g, hours.toString());
// 分钟替换
str = str.replace(/mm/g, minutes.toString().padStart(2, '0'));
str = str.replace(/m/g, minutes.toString());
// 秒替换
str = str.replace(/ss|SS/g, seconds.toString().padStart(2, '0'));
str = str.replace(/s|S/g, seconds.toString());
return str;
}
const formatDate = function(date = new Date(),formatStr = "yyyy-MM-dd HH:mm:ss") {
let str = formatStr;
const Week = ['日', '一', '二', '三', '四', '五', '六'];
const year = date.getFullYear();
const month = date.getMonth() + 1; // 月份修正为1-12
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const weekday = date.getDay();
// 年替换
str = str.replace(/yyyy|YYYY/g, year);
str = str.replace(/yy|YY/g, (year % 100).toString().padStart(2, '0'));
// 月替换
str = str.replace(/MM/g, month.toString().padStart(2, '0'));
str = str.replace(/M/g, month.toString());
// 周替换
str = str.replace(/w|W/g, Week[weekday]);
// 日替换
str = str.replace(/dd|DD/g, day.toString().padStart(2, '0'));
str = str.replace(/d|D/g, day.toString());
// 小时替换
str = str.replace(/hh|HH/g, hours.toString().padStart(2, '0'));
str = str.replace(/h|H/g, hours.toString());
// 分钟替换
str = str.replace(/mm/g, minutes.toString().padStart(2, '0'));
str = str.replace(/m/g, minutes.toString());
// 秒替换
str = str.replace(/ss|SS/g, seconds.toString().padStart(2, '0'));
str = str.replace(/s|S/g, seconds.toString());
return str;
}
/**
* 日期计算
* @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
* @param num int
* @param date Date 日期对象
* @return Date 返回日期对象
*/
const dateAdd = function(strInterval, num, date){
date = arguments[2] || new Date();
switch (strInterval) {
case 's' :return new Date(date.getTime() + (1000 * num));
case 'n' :return new Date(date.getTime() + (60000 * num));
case 'h' :return new Date(date.getTime() + (3600000 * num));
case 'd' :return new Date(date.getTime() + (86400000 * num));
case 'w' :return new Date(date.getTime() + ((86400000 * 7) * num));
case 'm' :return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
case 'y' :return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
}
}
/**
* 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串
* @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
* @param dtStart Date 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
* @param dtEnd Date 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
*/
const dateDiff = function(strInterval, dtStart, dtEnd) {
switch (strInterval) {
case 's' :return parseInt((dtEnd - dtStart) / 1000);
case 'n' :return parseInt((dtEnd - dtStart) / 60000);
case 'h' :return parseInt((dtEnd - dtStart) / 3600000);
case 'd' :return parseInt((dtEnd - dtStart) / 86400000);
case 'w' :return parseInt((dtEnd - dtStart) / (86400000 * 7));
case 'm' :return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);
case 'y' :return dtEnd.getFullYear() - dtStart.getFullYear();
}
}
/**
* 字符串转换为日期对象
* @param date Date 格式为yyyy-MM-dd HH:mm:ss,必须按年月日时分秒的顺序,中间分隔符不限制
*/
const strToDate = function(dateStr){
let data = dateStr;
let reCat = /(\d{1,4})/gm;
let t = data.match(reCat);
t[1] = t[1] - 1;
eval('var d = new Date('+t.join(',')+');');
return d;
}
/**
* 把指定格式的字符串转换为日期对象yyyy-MM-dd HH:mm:ss
*
*/
const strFormatToDate = function(formatStr, dateStr){
let year = 0;
let start = -1;
const len = dateStr.length;
if((start = formatStr.indexOf('yyyy')) > -1 && start < len){
year = dateStr.substr(start, 4);
}
let month = 0;
if((start = formatStr.indexOf('MM')) > -1 && start < len){
month = parseInt(dateStr.substr(start, 2)) - 1;
}
let day = 0;
if((start = formatStr.indexOf('dd')) > -1 && start < len){
day = parseInt(dateStr.substr(start, 2));
}
let hour = 0;
if( ((start = formatStr.indexOf('HH')) > -1 || (start = formatStr.indexOf('hh')) > 1) && start < len){
hour = parseInt(dateStr.substr(start, 2));
}
let minute = 0;
if((start = formatStr.indexOf('mm')) > -1 && start < len){
minute = dateStr.substr(start, 2);
}
let second = 0;
if((start = formatStr.indexOf('ss')) > -1 && start < len){
second = dateStr.substr(start, 2);
}
return new Date(year, month, day, hour, minute, second);
}
/**
* 日期对象转换为毫秒数
*/
const dateToLong = function(date){
return date.getTime();
}
/**
* 毫秒转换为日期对象
* @param dateVal number 日期的毫秒数
*/
const longToDate = function(dateVal){
return new Date(dateVal);
}
/**
* 判断字符串是否为日期格式
* @param str string 字符串
* @param formatStr string 日期格式, 如下 yyyy-MM-dd
*/
const isDate = function(str, formatStr){
if (formatStr == null){
formatStr = "yyyyMMdd";
}
const yIndex = formatStr.indexOf("yyyy");
if(yIndex==-1){
return false;
}
const year = str.substring(yIndex,yIndex+4);
const mIndex = formatStr.indexOf("MM");
if(mIndex==-1){
return false;
}
const month = str.substring(mIndex,mIndex+2);
const dIndex = formatStr.indexOf("dd");
if(dIndex==-1){
return false;
}
const day = str.substring(dIndex,dIndex+2);
if(!isNumber(year)||year>"2100" || year< "1900"){
return false;
}
if(!isNumber(month)||month>"12" || month< "01"){
return false;
}
if(day>getMaxDay(year,month) || day< "01"){
return false;
}
return true;
}
const getMaxDay = function(year,month) {
if(month==4||month==6||month==9||month==11)
return "30";
if(month==2)
if(year%4==0&&year%100!=0 || year%400==0)
return "29";
else
return "28";
return "31";
}
/**
* 变量是否为数字
*/
const isNumber = function(str)
{
const regExp = /^\d+$/g;
return regExp.test(str);
}
/**
* 把日期分割成数组 [年、月、日、时、分、秒]
*/
const toArray = function(myDate)
{
myDate = arguments[0] || new Date();
const myArray = [];
myArray[0] = myDate.getFullYear();
myArray[1] = myDate.getMonth();
myArray[2] = myDate.getDate();
myArray[3] = myDate.getHours();
myArray[4] = myDate.getMinutes();
myArray[5] = myDate.getSeconds();
return myArray;
}
/**
* 取得日期数据信息
* 参数 interval 表示数据类型
* y 年 M月 d日 w星期 ww周 h时 n分 s秒
*/
const datePart = function(interval, myDate)
{
myDate = arguments[1] || new Date();
let partStr='';
const Week = ['日','一','二','三','四','五','六'];
switch (interval)
{
case 'y' :partStr = myDate.getFullYear();break;
case 'M' :partStr = myDate.getMonth()+1;break;
case 'd' :partStr = myDate.getDate();break;
case 'w' :partStr = Week[myDate.getDay()];break;
case 'ww' :partStr = myDate.WeekNumOfYear();break;
case 'h' :partStr = myDate.getHours();break;
case 'm' :partStr = myDate.getMinutes();break;
case 's' :partStr = myDate.getSeconds();break;
}
return partStr;
}
/**
* 取得当前日期所在月的最大天数
*/
const maxDayOfDate = function(date)
{
date = arguments[0] || new Date();
date.setDate(1);
date.setMonth(date.getMonth() + 1);
const time = date.getTime() - 24 * 60 * 60 * 1000;
const newDate = new Date(time);
return newDate.getDate();
}
/**
* 2021年9月16日 11:19:16 chanchaw
* 传入一个日期返回该日期所在月份的最大天数
*/
const getMonthMaxDay = function(date)
{
date = arguments[0] || new Date();
// 传入的是字符串类型的日期则转换为日期类型对象
if( typeof(date) == 'string' )
date = strToDate(date)
date.setDate(1);
date.setMonth(date.getMonth() + 1);
const time = date.getTime() - 24 * 60 * 60 * 1000;
const newDate = new Date(time);
return newDate.getDate();
}
/**
* 2021年9月16日 11:20:33 chanchaw
* 返回上个月最后一天的日期
*/
const lastMonthLastDay = function()
{
const firstDay = curMonthFirstDay();// 获取当月的第一天
return dateAdd('d',-1,firstDay);
}
/**
* 2021年9月16日 12:10:44 chanchaw
* 获取当月的第一天,0点0分
*/
const curMonthFirstDay = function() {
const nowDay = new Date();
const curMonth = nowDay.getMonth() + 1;// 获取当月月份
const firstDay = String(nowDay.getFullYear()) + '-' + String(curMonth.toString()) + '-01';// 获取当月第一天
return strToDate(firstDay);
}
export { isLeapYear,dateToStr,formatDate,dateAdd,dateDiff,strToDate,strFormatToDate,dateToLong,longToDate,isDate,getMaxDay,isNumber,toArray,datePart,maxDayOfDate,getMonthMaxDay,lastMonthLastDay,curMonthFirstDay }
