这是我参与新手入门的第0篇文章,慌的一批,欢迎各位大佬在评论区提意见·。· 文末有干货🍔。
基础概念
ECMAScript 的 Date 类型参考了 Java 早期版本中的 java.util.Date。为此,Date 类型将日期 保存为自协调世界时(UTC,Universal Time Coordinated)时间 1970 年 1 月 1 日午夜(零时)至今所 经过的毫秒数。使用这种存储格式,Date 类型可以精确表示 1970 年 1 月 1 日之前及之后285616年的日期。
如何使用
语法
要创建日期对象,就使用 new 操作符来调用 Date 构造函数,语法:
new Date();
new Date(value);
new Date(dateString);
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
上述代码也是Date()
构造函数的四种基本形式,用法如下:
-
没有参数
如果没有提供参数,那么新创建的Date对象表示实例化时刻的日期和时间。
new Date() // Mon Jul 05 2021 14:50:15 GMT+0800 (中国标准时间)
-
Unix时间戳
value
一个 Unix 时间戳,时间戳是一个整数值,表示自1970年1月1日00:00:00 UTC(the Unix epoch)以来的毫秒数,忽略了闰秒,若 value 为负数,则表示1970年1月1日00:00:00 之前的日期。请注意大多数 Unix 时间戳功能仅精确到最接近的秒。
new Date(1625467815913) //Mon Jul 05 2021 14:50:15 GMT+0800 (中国标准时间) new Date(-1625467815913) //Sun Jun 30 1918 01:09:44 GMT+0800 (中国标准时间)
-
时间戳字符串
dateString
表示日期的字符串值。该字符串应该能被
Date.parse()
正确方法识别。如果dateString
并不表示日期,则该方法会返回 NaN。如果直接把表示日期的字符串传给 Date 构造函数,那么 Date 会在后台调用Date.parse()
。new Date('2021-07-05 15:25:00') //Mon Jul 05 2021 15:25:00 GMT+0800 (中国标准时间) new Date('2021/07/05 15:25:00') //Mon Jul 05 2021 15:25:00 GMT+0800 (中国标准时间) new Date('Mon Jul 05 2021 15:25:00') //Mon Jul 05 2021 15:25:00 GMT+0800 (中国标准时间)
-
分别提供日期与时间的每一个成员
当至少提供了年份与月份时,这一形式的
Date()
返回的Date
对象中的每一个成员都来自下列参数。没有提供的成员将使用最小可能值(对日期为1
,其他为0
)。year
表示年份的整数值。 0到99会被映射至1900年至1999年,其它值代表实际年份。monthIndex
表示月份的整数值,从 0(1月)到 11(12月),monthIndex
是从“0”开始计算的,这就意味着一月份为“0”,十二月份为“11”。date
可选 表示一个月中的第几天的整数值,从1开始。默认值为1。hours
可选 表示一天中的小时数的整数值 (24小时制)。默认值为0(午夜)。minutes
可选 表示一个完整时间(如 01:10:00)中的分钟部分的整数值。默认值为0。seconds
可选 表示一个完整时间(如 01:10:00)中的秒部分的整数值。默认值为0。milliseconds
可选 表示一个完整时间的毫秒部分的整数值。默认值为0。new Date(2021,6,5,15,22,00) //Mon Jul 05 2021 15:22:00 GMT+0800 (中国标准时间)
注意
不同的浏览器对 Date 类型的实现有很多问题。比如,很多浏览器会选择用当前日期替代越界的日期,因此有些浏览器会将"January 32, 2019"解释为"February 1,2019"。Opera 则会插入当前月的当前日,返回"January 当前日, 2019"。就是说,如果是在 9 月 21 日运行代码,会返回"January 21, 2019"。
属性
-
允许为
Date
对象添加属性。 -
Date.length
Date.length
的值是 7。这是该构造函数可接受的参数个数。
方法
-
返回自 1970-1-1 00:00:00 UTC(世界标准时间)至今所经过的毫秒数。等同于
new Date().getTime()
,区别在于Date.now()
不会创建额外Date
对象。Date.now() //1625473495744 new Date().getTime() //1625473495744
-
解析一个表示日期的字符串,并返回从 1970-1-1 00:00:00 所经过的毫秒数。
-
接受和构造函数最长形式的参数相同的参数(从2到7),并返回从 1970-01-01 00:00:00 UTC 开始所经过的毫秒数。
Date实例
所有的 Date
实例都继承自 Date.prototype
。修改 Date
构造函数的原型对象会影响到所有的 Date
实例。
实例属性
-
Date.prototype.constructor
返回创建了实例的构造函数,默认是
Date
构造函数。
实例方法
一下列出了常用的实例方法,更多方法可参考 developer.mozilla.org/zh-CN/docs/…
Getter
-
根据本地时间返回指定日期对象的月份中的第几天(1-31)。
-
根据本地时间返回指定日期对象的星期中的第几天(0-6)。
-
根据本地时间返回指定日期对象的年份(四位数年份时返回四位数字)。
-
根据本地时间返回指定日期对象的小时(0-23)。
-
根据本地时间返回指定日期对象的分钟(0-59)。
-
根据本地时间返回指定日期对象的月份(0-11)。
-
根据本地时间返回指定日期对象的秒数(0-59)。
-
返回从1970-1-1 00:00:00 UTC(协调世界时)到该日期经过的毫秒数,对于1970-1-1 00:00:00 UTC之前的时间返回负值。
Setter
-
根据本地时间为指定的日期对象设置月份中的第几天。
-
根据本地时间为指定日期对象设置完整年份(四位数年份是四个数字)。
-
根据本地时间为指定日期对象设置小时数。
-
根据本地时间为指定日期对象设置分钟数。
-
根据本地时间为指定日期对象设置月份。
-
根据本地时间为指定日期对象设置秒数。
-
通过指定从 1970-1-1 00:00:00 UTC 开始经过的毫秒数来设置日期对象的时间,对于早于 1970-1-1 00:00:00 UTC的时间可使用负值。
常用方法(全是干货,欢迎评论区补充!!!)
根据Date实例提供的方法,结合日常工作工作中的需求,总结了一下几个方法
- 返回一个包含各种日期格式的对象 ,不够用的话自己加就行,方便管理和复用
function formatDate(dateStr){
if(!dateStr) {return}
let _date = dateStr
if (typeof dateStr == 'string') {
_date = new Date(str_date.replace(/-/g, "/"))
}
if (typeof _date != 'object') {
return {};
}
// 小于10时补0
function fix(num) {
return (String(num)).padStart(2,0)
}
// yyyy-MM-dd HH:mm:ss
var year = _date.getFullYear()
, month = _date.getMonth() + 1
, date = _date.getDate()
, day = _date.getDay()
, hours = _date.getHours()
, minutes = _date.getMinutes()
, seconds = _date.getSeconds();
var months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
, months_en = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
, months_abbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
, days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
, days_en = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thurday', 'Friday', 'Saturday']
, days_abbr = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
return {
year: year,
month: fix(month),
date: fix(date),
day: day,
hours: fix(hours),
minutes: fix(minutes),
seconds: fix(seconds),
month_name: months[month - 1],
month_name_en: months_en[month - 1],
month_abbr: months_abbr[month - 1],
day_name: days[day],
day_name_en: days_en[day],
day_abbr: days_abbr[day],
// yyyy-MM-dd
ymd: year + '-' + fix(month) + '-' + fix(date),
// yyyy.MM.dd
ymd2: year + '.' + fix(month) + '.' + fix(date),
// HH:mm:ss
hms: fix(hours) + ':' + fix(minutes) + ':' + fix(seconds),
// HH:mm
hm: fix(hours) + ':' + fix(minutes),
// yyyy-MM-dd HH:mm:ss
full: year + '-' + fix(month) + '-' + fix(date) + ' ' + fix(hours) + ':' + fix(minutes) + ':' + fix(seconds),
// yyyy.MM.dd HH:mm:ss
full2: year + '.' + fix(month) + '.' + fix(date) + ' ' + fix(hours) + ':' + fix(minutes) + ':' + fix(seconds),
// yyyy/MM/dd HH:mm
ymdhm: year + '/' + fix(month) + '/' + fix(date) + ' ' + fix(hours) + ':' + fix(minutes),
// yy/MM/dd HH:mm
ymdhm2: (year + '').substring(2, 4) + '/' + fix(month) + '/' + fix(date) + ' ' + fix(hours) + ':' + fix(minutes),
// MM/dd HH:mm
mdhm: fix(month) + '/' + fix(date) + ' ' + fix(hours) + ':' + fix(minutes),
// dd month yyyy HH:mm
west: fix(date) + ' ' + months_abbr[month - 1] + ' ' + year + ' ' + fix(hours) + ':' + fix(minutes)
};
}
formatDate(new Date())
// {
// date: "05"
// day: 1
// day_abbr: "Mon"
// day_name: "周一"
// day_name_en: "Monday"
// full: "2021-07-05 17:05:02"
// full2: "2021.07.05 17:05:02"
// hm: "17:05"
// hms: "17:05:02"
// hours: "17"
// mdhm: "07/05 17:05"
// minutes: "05"
// month: "07"
// month_abbr: "Jul"
// month_name: "七月"
// month_name_en: "July"
// seconds: "02"
// west: "05 Jul 2021 17:05"
// year: 2021
// ymd: "2021-07-05"
// ymd2: "2021.07.05"
// ymdhm: "2021/07/05 17:05"
// ymdhm2: "21/07/05 17:05"
// }
- 返回一个由 开始时间 和 结束时间 组成的数组,获取快捷键日期 本月
currentMounth
、上月prevMounth
、本周currentWeek
、上周prevWeek
(不传入tag默认本月)
function getShortkeyDate(tag){
const tempDate = new Date().getDate(); // 当前几号
const tempDay = new Date().getDay() ? new Date().getDay() : 7; // 当前周几
const currentDate = new Date(); // 当前日期
let end = new Date();
let start = new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * (tempDate-1));
if(tag == 'currentMounth'){
end = new Date();
start = new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * (tempDate-1));
} else if(tag == 'currentWeek'){
end = new Date();
start = new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * (tempDay-1));
} else if(tag == 'prevMounth'){
end = new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * tempDate);
const endTempDate = new Date(end).getDate(); // 上个月最后一天是几号
start = new Date(end).setTime(new Date(end).getTime() - 3600 * 1000 * 24 * (endTempDate-1));
} else if(tag == 'prevWeek'){
end = new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * tempDay);
start = new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * (tempDay-1+7));
}
return [new Date(start), new Date(end)]
}
getShortkeyDate('currentMounth')
//[Thu Jul 01 2021 17:30:11 GMT+0800 (中国标准时间), Mon Jul 05 2021 17:30:11 GMT+0800 (中国标准时间)]
- 获取当前日期的上个月日期,一般用于获取近30天日期,返回一个表示日期的字符串
function getPreMonth(date) {
let arr = date.split('-');
let year = arr[0]; //获取当前日期的年份
let month = arr[1]; //获取当前日期的月份
let day = arr[2]; //获取当前日期的日
let days = new Date(year, month, 0);
days = days.getDate(); //获取当前日期中月的天数
let year2 = year;
let month2 = parseInt(month) - 1;
if (month2 == 0) {
year2 = parseInt(year2) - 1;
month2 = 12;
}
let day2 = day;
let days2 = new Date(year2, month2, 0);
days2 = days2.getDate();
if (day2 > days2) {
day2 = days2;
}
if (month2 < 10) {
month2 = '0' + month2;
}
let t2 = year2 + '-' + month2 + '-' + day2;
return t2;
}
getPreMonth('2021-07-31') //"2021-06-30"
getPreMonth('2021-01-01') //"2020-12-01"
- 获取两个时间段的每一天,一般用来处理渲染图表用,自己根据日期判断有无数据,没有的话就造一个,返回一个包含 开始时间 至 结束时间 之间每一天日期的数组
function formatEveryDay(start, end) {
let dateList = [];
let startTime = new Date(start);
let endTime = new Date(end);
while ((endTime.getTime() - startTime.getTime()) >= 0) {
let year = startTime.getFullYear();
let month = (String(startTime.getMonth() + 1)).padStart(2,0);
let day = (String(startTime.getDate())).padStart(2,0);
dateList.push(year + "-" + month + "-" + day);
startTime.setDate(startTime.getDate() + 1);
}
return dateList;
}
formatEveryDay('2021-07-01', '2021-07-05')
// ["2021-07-01", "2021-07-02", "2021-07-03", "2021-07-04", "2021-07-05"]
- 获取num天前/后的日期,num是正数表示之后的时间,num负数表示之前的时间,0表示今天,返回一个表示日期的字符串
function getFormatXDate(num) {
let date = new Date();
date.setDate(date.getDate() + num);
let Y = date.getFullYear()
let M = (date.getMonth() + 1) < 10? "0"+ (date.getMonth() + 1) : date.getMonth() + 1
let D = date.getDate()< 10? "0" + date.getDate() : date.getDate()
let time = Y+"-"+M+"-"+D;
return time;
}
// 今天日期
getFormatXDate(0) //"2021-07-05"
// 4天后的日期,当前日期为2021-07-05
getFormatXDate(4) //"2021-07-09"
// 8天前的日期
getFormatXDate(-8) //"2021-06-27"
总结
也不知道有没有人能看到总结,随便洒洒水·。·一直都有写文章的想法,奈何文笔不行加之觉得自己前端方面学识浅薄,没法输出优质的文章,好多次打开wolai
却也只是停留在新建模板这步。转念一想还是尝试一下吧,万事开头难,慢慢掌握技巧,写的多了就好了,冲冲冲。