現在JavaScript日期–如何在JavaScript中獲取當前日期

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/mmyyyy-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對象有更好的了解。 您還可以使用其他第三方庫(例如datesjmoment來處理應用程序中的日期。

Until next time, stay safe and keep hustling.

在下一次之前,請保持安全并保持忙碌狀態。

翻譯自: https://www.freecodecamp.org/news/javascript-date-now-how-to-get-the-current-date-in-javascript/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390291.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390291.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390291.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

233. 數字 1 的個數

給定一個整數 n,計算所有小于等于 n 的非負整數中數字 1 出現的個數。 示例 1: 輸入:n 13 輸出:6 示例 2: 輸入:n 0 輸出:0 解題思路 正確性證明 例如:對于n3015&#xff0c…

Linux串口設置參數

為什么80%的碼農都做不了架構師?>>> 在Linux環境下,串口名從ttyS0開始依次是ttyS1、ttyS2等。在本程序中,使用ttyS0作為通信串口。在打開ttyS0的時候選項 O_NOCTTY 表示不能把本串口當成控制終端,否則用戶的鍵盤輸入信…

STM32F013 十元板

我大拇指般大小。STM32F103C8T6,64K Flash,20K RAM,m3的核。十元,應該是價格極限了吧。 通過USB供電(5V),也可以排針3.3V供電。可惜沒有引出5V排針。USB口可以供電和USB通訊,沒有USB…

如何在Python中建立和訓練K最近鄰和K-Means集群ML模型

One of machine learnings most popular applications is in solving classification problems.機器學習最流行的應用之一是解決分類問題。 Classification problems are situations where you have a data set, and you want to classify observations from that data set in…

552. 學生出勤記錄 II

552. 學生出勤記錄 II 可以用字符串表示一個學生的出勤記錄,其中的每個字符用來標記當天的出勤情況(缺勤、遲到、到場)。記錄中只含下面三種字符: ‘A’:Absent,缺勤 ‘L’:Late,遲…

C/C++中計算函數運行時間

#include<stdio.h> #include<time.h> clock_t start,stop;//clock_t 是clock&#xff08;&#xff09;函數返回變量的類型 double duration;//記錄被測函數的運行時間&#xff0c;以秒為單位 int main() { startclock();//開始計時 MyFunction();//把被測函數加在這…

作為一名前端開發工程師,你必須掌握的WEB模板引擎:Handlebars

為什么需要使用模板引擎&#xff1f; 關于為什么要使用模板引擎&#xff0c;按照我常說的一句話就是&#xff1a;不用重復造輪子了。 簡單來說&#xff0c;模板最本質的作用是“變靜為動”&#xff0c;一切利于這方面的都是優勢&#xff0c;不利于的都是劣勢。要想很好地實現“…

extjs 實用開發指南_如何提出有效問題:針對開發人員的實用指南

extjs 實用開發指南Learning is a journey that never ends. At every point in your career, you will keep learning, re-learning, and un-learning. 學習是一個永無止境的旅程。 在職業生涯的每個階段&#xff0c;您都會不斷學習&#xff0c;重新學習和不學習。 The abil…

LOJ 6270

最近&#xff08;一直&#xff09;有點&#xff08;很&#xff09;蠢 按照區間大小排序做區間包含多少區間的話 只用考慮 左端點比當前左端點小的和右端點比當前右端點大的&#xff0c;因為不可能同時滿足 關于K&#xff0c;就在做到K的時候減一下就好了&#xff0c;一直傻逼在…

Zabbix3.4安裝詳細步驟

Zabbix3.4安裝的詳細步驟一、zabbix介紹現在大多數公司都會用到監控軟件&#xff0c;主流的監控軟件就是Zabbix了&#xff0c;當然還會有Nagios等其他的軟件&#xff1a;zabbix是一個基于WEB界面的提供分布式系統監視以及網絡監視功能的企業級的開源解決方案。zabbix能監視各種…

軟件自學成才到公司要學歷嗎_作為一名自學成才的移動開發人員,我在旅途中學到了什么

軟件自學成才到公司要學歷嗎In this post, Ill share my entire journey about how I became a professional mobile developer.在這篇文章中&#xff0c;我將分享我如何成為一名專業的移動開發人員的整個過程。 I hope that reading about my experience will help you refle…

cs231n---語義分割 物體定位 物體檢測 物體分割

1 語義分割 語義分割是對圖像中每個像素作分類&#xff0c;不區分物體&#xff0c;只關心像素。如下&#xff1a; &#xff08;1&#xff09;完全的卷積網絡架構 處理語義分割問題可以使用下面的模型&#xff1a; 其中我們經過多個卷積層處理&#xff0c;最終輸出體的維度是C*H…

http協議內容

前言&#xff1a; http協議&#xff1a; 對瀏覽器客戶端 和 服務器端 之間數據傳輸的格式規范http1.0&#xff1a;當前瀏覽器客戶端與服務器端建立連接之后&#xff0c; 只能發送一次請求&#xff0c;一次請求之后連接關閉。 http1.1&#xff1a;當前瀏覽器客戶端與服務器端建…

array_combine()

轉載于:https://www.cnblogs.com/xiaobiaomei/p/8392728.html

CSS外邊距(margin)重疊及防止方法

#css外邊距margin重疊及防止方法CSS外邊距(margin)重疊及防止方法 #1-什么是外邊距margin重疊1. 什么是外邊距(margin)重疊 外邊距重疊是指兩個或多個盒子(可能相鄰也可能嵌套)的相鄰邊界(其間沒有任何非空內容、補白、邊框)重合在一起而形成一個單一邊界。 #2-相鄰marign重疊的…

composer windows安裝

一.前期準備: 1.下載安裝包,https://getcomposer.org/download/ 2.在php.ini文檔中打開extensionphp_openssl.dll 3.下載php_ssh2.dll、php_ssh2.pdb,http://windows.php.net/downloads/pecl/releases/ssh2/0.12/ 4.把php_ssh2.dll、php_ssh2.pdb文件放php的ext文件夾 5.重啟ap…

spring整合mybatis采坑

本來這個錯誤是整合spring和mybatis遇到的錯誤&#xff0c;但是一直沒有解決&#xff0c;但是在做SpringMVC時也了出現了這樣的錯誤org.springframework.beans.factory.BeanCreationException: Error creating bean with name sqlSessionFactory defined in class path resourc…

處理測試環境硬盤爆滿

測試環境經常會收到這類告警 第一步 登陸機器查看硬盤使用 執行df 好吧,使用情況真不妙,根目錄占用過大 第二步 確定哪個文件太大或者文件過多 進入爆滿的目錄,如這里是根目錄 cd / 然后找下面哪個文件夾或者文件太大,有幾種方式: 1.dusudo du -h --max-depth1 | sort -hr 越前…

LeetCode-46. Permutations

一、問題描述 就是全排列問題。 二、問題解決 應該哪一本數據結構的書上都有講了。 void get_permute(vector<int>& nums, int pos, vector<vector<int>>& result) {if (nums.size() pos) {result.push_back(nums);return;}for (int i pos; i <…

web操作系統開發的_哪種操作系統更適合Web開發

web操作系統開發的If youre new to web development and are in the market for a new laptop, you might be wondering which operating system is best.如果您是Web開發的新手&#xff0c;并且正在購買新的筆記本電腦&#xff0c;您可能想知道哪種操作系統是最好的。 Spoile…