const date = new Date();
该 Date 对象包含一个 Number,表示从新纪元(即1970年1月1日)起经过的毫秒数。
您可以将日期字符串传递给 Date 构造函数以创建指定日期的对象:
const date = new Date('Jul 12 2011');
要获取当前年份,可以使用Date对象的 getFullYear() 实例方法 。getFullYear() 方法返回日期对应的年份:
const currentYear = date.getFullYear(); console.log(currentYear); //2020
同样,有一些方法可以获取当月的当前日期和当前的月份:
const today = date.getDate(); const currentMonth = date.getMonth() + 1;
getDate() 方法返回当月的当前日期(1-31)。
getMonth() 方法返回指定日期的月份。需要注意的一点是, getMonth()方法返回的是索引值(0-11),其中0表示一月,11表示十二月。因此,加1可以使月份的值标准化。
Date.now()
now() 是 Date 对象的静态方法。它返回以毫秒为单位的值,该值表示自纪元以来经过的时间。您可以将now()方法返回的毫秒数传递给Date 构造函数以实例化新的 Date 对象:
const timeElapsed = Date.now(); const today = new Date(timeElapsed);
today.toDateString(); // "Sun Jun 14 2020"
toISOString()方法返回遵循ISO 8601扩展格式的日期:
today.toISOString(); // "2020-06-13T18:30:00.000Z"
toUTCString()方法以UTC时区格式返回日期:
today.toUTCString(); // "Sat, 13 Jun 2020 18:30:00 GMT"
toLocaleDateString()方法以对地区敏感的格式返回日期:
today.toLocaleDateString(); // "6/14/2020"
我们可以在MDN文档中找到Date有关方法的完整参考。
自定义日期格式化工具
除了上一节中提到的格式外,我们开发应用程序可能具有不同的数据格式。它可以是yy年mm月dd日或yyyy-dd-mm格式,或者类似的东西。
为了解决这个问题,最好创建一个可重用的日期格式化函数,以便可以在多个项目中使用它。
因此,在本节中,我们会创建一个函数,该函数将接收时间格式作为参数,返回对应格式的日期:
const today = new Date(); function formatDate(date, format) {
// } formatDate(today, 'mm/dd/yy');
format.replace('mm', date.getMonth() + 1);
但这样会形成链式调用,而且会影响我们函数的灵活度:
format.replace('mm', date.getMonth() + 1) .replace('yy', date.getFullYear()) .replace('dd', date.getDate());
所以我们可以使用正则表达式代替方法来replace()。
首先创建一个对象,该对象将代表子字符串的键值对及其各自的值:
const formatMap = {
mm: date.getMonth() + 1, dd: date.getDate(), yy: date.getFullYear().toString().slice(-2), yyyy: date.getFullYear() };
接下来,使用正则表达式匹配并替换字符串:
formattedDate = format.replace(/mm|dd|yy|yyy/gi, matched => map[matched]);
完整的功能如下所示:
function formatDate(date, format) {
const map = {
mm: date.getMonth() + 1, dd: date.getDate(), yy: date.getFullYear().toString().slice(-2), yyyy: date.getFullYear() } return format.replace(/mm|dd|yy|yyy/gi, matched => map[matched]) }
总结
希望通过这篇文章,能让你对JavaScript 中的Date对象有更好的了解。
其实你还可以使用其他第三方库(例如datesj和moment)来处理日期。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/204528.html原文链接:https://javaforall.net
