JavaScript Date

333 阅读5分钟

JavaScript Date 详解

Date对象用于处理日期和时间,可以通过new关键词来定义Date对象。

创建方式

new Date(); 
new Date(value); 
new Date(dateString); 
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

year:表示年份的整数值。0到99会被映射至1900年至1999年,其它值代表实际年份。

monthIndex:是从0开始计算的,这就意味着一月份为0,十二月份为11

当Date作为构造函数调用并传入多个参数时,如果数值大于合理范围时(如月份为 13 或者分钟数为 70),相邻的数值会被调整。比如 new Date(2013, 13, 1)等于new Date(2014, 1, 1),它们都表示日期2014-02-01(注意月份是从0开始的)

上面的参数大多数是可选的,在不指定的情况,默认参数是0。如果提供了至少两个参数,day默认是1。

let methodOneDate = new Date();
console.log('methodOneDate=>',methodOneDate);
let methodTwoDate = new Date('October 13, 1975 11:13:00');
console.log('methodTwoDate=>',methodTwoDate);
let methodThreeDate = new Date(79,5,24);
console.log('methodThreeDate=>',methodThreeDate);
let methodFourDate = new Date(79,5,24,11,33,0);
console.log('methodFourDate=>',methodFourDate);

执行结果如下:

1667894488006-dd43b77b-8e0d-4b03-a8ba-7648262652cf.png

日期配置

通过使用针对日期对象的方法,可以很容易的对日期进行操作。

// 为日期对象设置了一个特定的日期 (2010 年 1 月 14 日)
let date=new Date();
date.setFullYear(2010,0,14);
console.log('日期配合demo1[date]=>',date);

执行结果如下:

1667895031164-e4f00152-574d-4509-b0e3-741d953ded70.png

// 将日期对象设置为 5 天后的日期
let date_=new Date();
date_.setDate(date_.getDate()+5);
console.log('日期配合demo2[date_]=>',date_);

执行结果如下:

image.png

注:如果增加天数会改变月份或者年份,日期会自动完成这种转换。关于日期对象的方法在文章后面会总结。

日期比较

日期对象支持两个对象作比较。

// 两个日期比较
// 首先创建一个日期标准
let standardDate = new Date();
standardDate.setFullYear(2012,11,21);
// 用当前日期与标准日期做比较
let currentDate = new Date();
if(currentDate > standardDate) console.log('After');
else console.log('Before');

执行结果如下:

1667896001728-eee047e7-f7ca-4a02-b5ee-cf02532ff478.png

封装Date函数

如果各位掘友有封装见解,请在评论区留言,小霍会及时添加,抱拳了!

/**
 * DateUtils.js
 * 封装Date()相关工具函数
 *
 * @author HuoYue
 * @time 2024年4月3日15:19:08
 */const $DU = {
    getCurrentYear,
    getCurrentMonth,
    getCurrentWeek,
    getCurrentTime,
    getResultOfAddingTimeAndDays,
    timeComparison,
    calculateNumberOfDaysBetweenTwoDates,
    getNumberOfDaysByYearAndMonth,
    customFormattedDate
};
​
/**
 * getCurrentYear()
 * 获取当前年度
 *
 * @return {number} 年度
 */
function getCurrentYear () {
    return new Date().getFullYear();
}
// const getCurrentYear = () => new Date().getFullYear();/**
 * getCurrentMonth()
 * 获取当前月份
 *
 * @return {number} 月份
 */
function getCurrentMonth () {
    return new Date().getMonth() + 1;
}
// const getCurrentMonth = () => new Date().getMonth() + 1;/**
 * getCurrentWeek()
 * 获取当前星期数
 *
 * @param prefix 星期|周 默认星期
 * @return {string} 星期字符串
 */
function getCurrentWeek(prefix = '星期') {
    return `${prefix}${'日一二三四五六'.charAt(new Date().getDay())}`
}
// const getCurrentWeek = (prefix = '星期') => `${prefix}${"日一二三四五六".charat(new Date().getDay())}`;/**
 * getCurrentTime()
 * 获取当前时间
 *
 * @return {Date} 格林威治标准时间格式(GMT)
 */
function getCurrentTime () {
    return new Date();
}
// const getCurrentTime = () => new Date();/**
 * getResultOfAddingTimeAndDays()
 * 获取时间和天数相加结果
 *
 * @param time 时间
 * @param days 天数
 * @return {Date} 格林威治标准时间格式(GMT)
 */
function getResultOfAddingTimeAndDays(time, days) {
    return new Date(time.getTime() + days * 24 * 60 * 60 * 1000);
}
// const getResultOfAddingTimeAndDays = (time, days) => new Date(time.getTime() + days * 24 * 60 * 60 * 1000);/**
 * timeComparison()
 * 时间比较
 *
 * @param time1
 * @param time2
 * @return {number} 时间差
 */
function timeComparison(time1, time2){
    return time1.getTime() - time2.getTime();
}
// const timeComparison = (time1, time2) => time1.getTime() - time2.getTime();/**
 * calculateNumberOfDaysBetweenTwoDates()
 * 计算两个日期之间相隔天数
 *
 * @param time1
 * @param time2
 * @return {number} 时间差(天数)
 */
function calculateNumberOfDaysBetweenTwoDates(time1, time2) {
    return (time1.getTime() - time2.getTime())/24 * 60 * 60 * 1000;
}
// const calculateNumberOfDaysBetweenTwoDates = (time1, time2) => (time1.getTime() - time2.getTime())/24 * 60 * 60 * 1000;/**
 * getNumberOfDaysByYearAndMonth()
 * 获取某年某月的天数
 *
 * @param year 年份
 * @param month 月份
 * @return {number} 天数
 */
function getNumberOfDaysByYearAndMonth(year, month) {
    return new Date(year, month, 0).getDate();
}
// const getNumberOfDaysByYearAndMonth = (year, month) => new Date(year, month, 0).getDate();/**
 * customFormattedDate()
 * 自定义格式化Date()
 * year: 年, yyyy: 公历年, MM: 公历月, dd: 公历日,week: 星期,MSECONDS: 计数毫秒,hh: 时,mm: 分,ss: 秒,ms: 毫秒,DS: 默认日期字符串, TS: 默认时间字符串,DTS: 默认日期时间拼接字符串
 * 注意: MSECONDS(计数毫秒)是从1970-1-1开始计算的
 *
 * @param dateString 时间字符串 获取当前时间时传''
 * @param format yyyy-MM-dd hh:mm:ss||yyyy-MM-dd hh:mm:ss:ms||...
 * @returns {*}
 */
function customFormattedDate(dateString, format) {
    let date;
    if (dateString && dateString !== '') new Date(Date.parse(dateString));
    else date = new Date();
    format = format || 'yyyy-MM-dd hh:mm:ss';
    let object = {
        'year': date.getYear(),
        'yyyy': date.getFullYear(),
        'MM': date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1),
        'dd': date.getDate() < 10 ? '0' + date.getDate() : date.getDate(),
        'week': date.getDay() === 0 ? 7 : date.getDay(),
        'MSECONDS': date.getTime(),
        'hh': date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
        'mm': date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
        'ss': date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(),
        'ms': date.getMilliseconds(),
        'DS': date.toLocaleDateString(),
        'TS': date.toLocaleTimeString(),
        'DTS': date.toLocaleString()
    };
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1, object.yyyy.toString().substr(4 - RegExp.$1.length));
    for (let key in object) {
        if (new RegExp('(' + key + ')').test(format)) format = format.replace(RegExp.$1, object[key]);
    }
    return format;
}
​
// ES6 导出
// export default $DU;

相关方法

方法描述
parse()根据这个字符串返回相应日期的毫秒数。 ECMA-262没有定义Date.parse()应该支持哪种日期格式,因此这个方法的行为因实现而异,而且通常是因地区而异。
UTC()根据世界时返回 1970 年 1 月 1 日 到指定日期的毫秒数。 但它与Date.parse()在构建值时使用的是不同的信息Date.UTC()的参数分别表示年份、基于0的月数(一月是0,二月是1,依次类推)、月中的哪一天(1到31)、小时数(0到23)、分钟、秒、毫秒数。在这些参数中只有前两个参数是必须的(年和月)
now()返回调用此方法的日期和时间的毫秒数。
getDate()从 Date 对象返回一个月中的某一天 (1 ~ 31)。
getDay()从 Date 对象返回一周中的某一天 (0 ~ 6)。
getFullYear()从 Date 对象以四位数字返回年份。
getHours()返回 Date 对象的小时 (0 ~ 23)。
getMilliseconds()返回 Date 对象的毫秒(0 ~ 999)。
getMinutes()返回 Date 对象的分钟 (0 ~ 59)。
getMonth()从 Date 对象返回月份 (0 ~ 11)。
getSeconds()返回 Date 对象的秒数 (0 ~ 59)。
getTime()返回 1970 年 1 月 1 日至今的毫秒数。
getTimezoneOffset()返回本地时间与格林威治标准时间 (GMT) 的分钟差。
getUTCDate()根据世界时从 Date 对象返回月中的一天 (1 ~ 31)。
getUTCDay()根据世界时从 Date 对象返回周中的一天 (0 ~ 6)。
getUTCFullYear()根据世界时从 Date 对象返回四位数的年份。
getUTCHours()根据世界时返回 Date 对象的小时 (0 ~ 23)。
getUTCMilliseconds()根据世界时返回 Date 对象的毫秒(0 ~ 999)。
getUTCMinutes()根据世界时返回 Date 对象的分钟 (0 ~ 59)。
getUTCMonth()根据世界时从 Date 对象返回月份 (0 ~ 11)。
getUTCSeconds()根据世界时返回 Date 对象的秒钟 (0 ~ 59)。
getYear()已废弃。 请使用 getFullYear() 方法代替。
parse()返回1970年1月1日午夜到指定日期(字符串)的毫秒数。
setDate()设置 Date 对象中月的某一天 (1 ~ 31)。
setFullYear()设置 Date 对象中的年份(四位数字)。
setHours()设置 Date 对象中的小时 (0 ~ 23)。
setMilliseconds()设置 Date 对象中的毫秒 (0 ~ 999)。
setMinutes()设置 Date 对象中的分钟 (0 ~ 59)。
setMonth()设置 Date 对象中月份 (0 ~ 11)。
setSeconds()设置 Date 对象中的秒钟 (0 ~ 59)。
setTime()setTime() 方法以毫秒设置 Date 对象。
setUTCDate()根据世界时设置 Date 对象中月份的一天 (1 ~ 31)。
setUTCFullYear()根据世界时设置 Date 对象中的年份(四位数字)。
setUTCHours()根据世界时设置 Date 对象中的小时 (0 ~ 23)。
setUTCMilliseconds()根据世界时设置 Date 对象中的毫秒 (0 ~ 999)。
setUTCMinutes()根据世界时设置 Date 对象中的分钟 (0 ~ 59)。
setUTCMonth()根据世界时设置 Date 对象中的月份 (0 ~ 11)。
setUTCSeconds()setUTCSeconds() 方法用于根据世界时 (UTC) 设置指定时间的秒字段。
setYear()已废弃。请使用 setFullYear() 方法代替。
toDateString()把 Date 对象的日期部分转换为字符串。
toGMTString()已废弃。请使用 toUTCString() 方法代替。
toISOString()使用 ISO 标准返回字符串的日期格式。
toJSON()以 JSON 数据格式返回日期字符串。
toLocaleDateString()根据本地时间格式,把 Date 对象的日期部分转换为字符串。
toLocaleTimeString()根据本地时间格式,把 Date 对象的时间部分转换为字符串。
toLocaleString()根据本地时间格式,把 Date 对象转换为字符串。
toString()把 Date 对象转换为字符串。
toTimeString()把 Date 对象的时间部分转换为字符串。
toUTCString()根据世界时,把 Date 对象转换为字符串。实例:var today = new Date(); var UTCstring = today.toUTCString();
valueOf()返回 Date 对象的原始值。