现在JavaScript日期–如何在JavaScript中获取当前日期
阅读Eloquent JavaScript提高JavaScript技能:https://eloquentjavascript.net/ #生活技巧# #工作学习技巧# #编程学习资源#
Many applications you build will have some sort of a date component, whether it's the creation date of a resource, or the timestamp of an activity.
您构建的许多应用程序都将具有某种日期组件,无论是资源的创建日期还是活动的时间戳。
Dealing with date and timestamp formatting can be exhausting. In this guide, you will learn how to get the current date in various formats in JavaScript.
处理日期和时间戳格式可能会很累。 在本指南中,您将学习如何在JavaScript中以各种格式获取当前日期。
JavaScript的Date对象 (JavaScript's Date Object)
JavaScript has a built-in Date object that stores the date and time and provides methods for handling them.
JavaScript具有一个内置的Date对象,该对象存储日期和时间并提供处理它们的方法。
To create a new instance of the Date object, use the new keyword:
要创建Date对象的新实例,请使用new关键字:
const date = new Date();'
The Date object contains a Number that represents milliseconds passed since the Epoch, that is 1 January 1970.
Date对象包含一个Number ,该Number表示自新纪元(即1970年1月1日)起经过的毫秒Number 。
You can pass a date string to the Date constructor to create an object for the specified date:
您可以将日期字符串传递给Date构造函数以创建指定日期的对象:
const date = new Date('Jul 12 2011');'
To get the current year, use the getFullYear() instance method of the Date object. The getFullYear() method returns the year of the specified date in the Date constructor:
要获取当前年份,请使用Date对象的getFullYear()实例方法。 getFullYear()方法在Date构造函数中返回指定日期的年份:
const currentYear = date.getFullYear();
console.log(currentYear);
Similarly, there are methods for getting the current day of the month and the current month:
同样,有一些方法可以获取当月的当前日期和当前的月份:
const today = date.getDate();
const currentMonth = date.getMonth() + 1;
The getDate() method returns the current day of the month (1-31).
getDate()方法返回当月的当前日期(1-31)。
The getMonth() method returns the month of the specified date. One point to note about the getMonth() method is that it returns 0-indexed values (0-11) where 0 is for January and 11 for December. Hence the addition of 1 to normalize the month's value.
getMonth()方法返回指定日期的月份。 关于getMonth()方法要注意的一点是,它返回0索引值(0-11),其中0表示一月,11表示十二月。 因此,加1以使月份值标准化。
现在约会 (Date now)
now() is a static method of the Date object. It returns the value in milliseconds that represents the time elapsed since the Epoch. You can pass in the milliseconds returned from the now() method into the Date constructor to instantiate a new Date object:
now()是Date对象的静态方法。 它返回以毫秒为单位的值,该值表示自纪元以来所经过的时间。 您可以将now()方法返回的毫秒数传递给Date构造函数,以实例化新的Date对象:
const timeElapsed = Date.now();
const today = new Date(timeElapsed);
'格式化日期 (Formatting The Date)
You can format the date into multiple formats (GMT, ISO, and so on) using the methods of the Date object.
您可以使用Date对象的方法将Date格式化为多种格式(GMT,ISO等)。
The toDateString() method returns the date in a human readable format:
toDateString()方法以人类可读的格式返回日期:
today.toDateString(); // "Sun Jun 14 2020"
The toISOString() method returns the date which follows the ISO 8601 Extended Format:
toISOString()方法返回遵循ISO 8601扩展格式的日期:
today.toISOString(); // "2020-06-13T18:30:00.000Z"
The toUTCString() method returns the date in UTC timezone format:
toUTCString()方法以UTC时区格式返回日期:
today.toUTCString(); // "Sat, 13 Jun 2020 18:30:00 GMT"
The toLocaleDateString() method returns the date in a locality-sensitive format:
toLocaleDateString()方法以对地区敏感的格式返回日期:
today.toLocaleDateString(); // "6/14/2020"
You can find the complete reference for the Date methods in the MDN documentation.
您可以在MDN文档中找到有关Date方法的完整参考。
自定义日期格式器功能 (Custom Date Formatter Function)
Apart from the formats mentioned in the above section, your application might have a different format for data. It could be in yy/dd/mm or yyyy-dd-mm format, or something similar.
除了上一节中提到的格式外,您的应用程序可能具有不同的数据格式。 它可以是yy/dd/mm或yyyy-dd-mm格式,或类似格式。
To tackle this problem, it would be better to create a reusable function so that it can be used across multiple projects.
为了解决这个问题,最好创建一个可重用的函数,以便可以在多个项目中使用它。
So in this section, let's create a utility function that will return the date in the format specified in the function argument:
因此,在本节中,让我们创建一个实用程序函数,该函数将以函数参数中指定的格式返回日期:
const today = new Date();
function formatDate(date, format) {
}
formatDate(today, 'mm/dd/yy');
'You need to replace the strings "mm", "dd", "yy" with the respective month, day and year values from the format string passed in the argument.
您需要使用参数中传递的格式字符串中的月份,日期和年份值分别替换字符串“ mm”,“ dd”,“ yy”。
To do that you can use the replace() method like shown below:
为此,可以使用如下所示的replace()方法:
format.replace('mm', date.getMonth() + 1);
But this will lead to a lot of method chaining and make it difficult to maintain as you try to make the function more flexible:
但是,这将导致很多方法链接,并在尝试使函数更灵活时难以维护:
format.replace('mm', date.getMonth() + 1)
.replace('yy', date.getFullYear())
.replace('dd', date.getDate());
Instead of chaining methods, you can make use of regular expression with the replace() method.
可以使用正则表达式和replace()方法来代替链接方法。
First create an object that will represent a key-value pair of the substring and its respective value:
首先创建一个对象,该对象将代表子字符串的键值对及其各自的值:
const formatMap = {
mm: date.getMonth() + 1,
dd: date.getDate(),
yy: date.getFullYear().toString().slice(-2),
yyyy: date.getFullYear()
};
Next, use regular expression to match and replace the strings:
接下来,使用正则表达式匹配并替换字符串:
formattedDate = format.replace(/mm|dd|yy|yyy/gi, matched => map[matched]);
The complete function looks like this:
完整的功能如下所示:
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])
}
'You can also add the ability to format timestamps in the function.
您还可以在函数中添加格式化时间戳的功能。
结论 (Conclusion)
I hope you now have a better understanding of the Date object in JavaScript. You can also use other third-party libraries like datesj and moment to handle dates in your application.
希望您现在对JavaScript中的Date对象有更好的了解。 您还可以使用其他第三方库(例如datesj和moment来处理应用程序中的日期。
Until next time, stay safe and keep hustling.
在下一次之前,请保持安全并保持忙碌状态。
翻译自: https://www.freecodecamp.org/news/javascript-date-now-how-to-get-the-current-date-in-javascript/
网址:现在JavaScript日期–如何在JavaScript中获取当前日期 https://www.yuejiaxmz.com/news/view/504039
相关内容
script type=“text/JavaScript”是什么关于:js怎么获取元素的自定义属性的问题(原生JavaScript)
JavaScript常用优化分享(三)
JavaScript作用域
javascript中等于(==)与全等(===)的区别说明
JavaScript 中,num = num
JavaScript 为什么要让that=this
JavaScript数据类型的特殊性(二)——typeof(null)=Object
自动化技术:用JavaScript打造轻松生活
JavaScript学习指南:从入门到精通,掌握核心技巧与实践方法