JavaScript >> Javascript 文檔 >  >> JavaScript

如何在 JavaScript 中獲取當前日期、月份和年份

Date 對象方法 getDate() , getMonth() , 和 getFullYear() 可用於從 JavaScript 中的日期對像中檢索日、月和全年。

這是一個例子:

const date = new Date(2021, 8, 18);

const day = date.getDate();
const month = date.getMonth() + 1; // getMonth() returns month from 0 to 11
const year = date.getFullYear();

const str = `${day}/${month}/${year}`;

console.log(str);
// 18/9/2021

注意 getDate() , getMonth() , 和 getFullYear() 方法返回運行代碼的計算機的本地時區的日期和時間。

要獲取通用時區 (UTC) 中的日期和時間,只需將上述方法替換為 getUTCDate() , getUTCMonth() , 和 getUTCFullYear() 分別:

const date = new Date(2021, 8, 18);

const day = date.getUTCDate();
const month = date.getUTCMonth() + 1; // getUTCMonth() returns month from 0 to 11
const year = date.getUTCFullYear();

const str = `${day}/${month}/${year}`;

console.log(str);
// 18/9/2021

Tutorial JavaScript 教程
  1. ~40 行純 js 代碼編輯器

  2. 如何發布我自己的 NPM 包?

  3. 平滑的 CSS 漸變過渡

  4. RxJS 簡化(不要失去你的彈珠)

  5. 使用 R 和 JavaScript 的 Code 2019-05 出現

  6. 在 jQuery 中聲明數組

  7. 傳遞函數作為參數 JavaScript |示例代碼

  1. 使用 FS Core 模塊在 NodeJS 中讀寫文件/目錄

  2. React - 無法讀取未定義的屬性映射

  3. 獲取系統當前日期和時間的*合法*方法是什麼?

  4. 如何使用樣式化組件構建響應式📱 React 導航菜單💻

  5. 如何在不知道 json 鍵的情況下在 react native 中獲取數據

  6. ⚡ 使用 Preact (1 LOC) 讓 Gatsby 更快

  7. 艱難地使用 Nodemailer 和 Mailgun

  1. 如何在 React Native 的右下角放置浮動操作按鈕

  2. 解析來自 Google 新聞的值

  3. 第 3 天:響應 useRef 掛鉤以滾動到 HTML 元素。

  4. 用歷史折疊引導程序:)