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); //2020
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/