JS獲取日期的多個方面

一、JS獲取日期是周幾

在前端開發中,我們經常需要獲取日期是周幾,在JS中,我們可以通過Date對象的getDay()方法獲取日期是周幾。

const weekDay = ['日', '一', '二', '三', '四', '五', '六'];
const date = new Date();
const day = weekDay[date.getDay()];

以上代碼中,weekDay數組存儲了每個星期幾的漢字,date.getDay()獲取當前日期是星期幾,通過數組下標獲取漢字表示。

二、JS獲取當前年月日時間戳

時間戳是指當前時間距離1970年1月1日0時0分0秒的毫秒數,JS中通過Date對象的getTime()方法可以獲取時間戳。

const date = new Date();
const timestamp = date.getTime();

以上代碼中,date.getTime()獲取當前日期的時間戳。

三、JS獲取日期年月日

JS中可以通過Date對象的getFullYear()、getMonth()和getDate()方法獲取年、月、日。

const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();

以上代碼中,getFullYear()獲取年份,getMonth()獲取月份(0表示一月,11表示十二月,因此需要加1),getDate()獲取日期。

四、JS獲取當前日期

除了獲取具體的年月日,我們還可以獲取當前的日期,格式為「星期幾 月份/日期/年份」。

const weekDay = ['日', '一', '二', '三', '四', '五', '六'];
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const dayOfWeek = weekDay[date.getDay()];
const currentDate = `星期${dayOfWeek} ${month}/${day}/${year}`;

以上代碼中,weekDay數組存儲了每個星期幾的漢字,date.getDay()獲取當前日期是星期幾,通過數組下標獲取漢字表示,構造currentDate字元串。

五、JS獲取日期方法

在JS中,可以通過new Date()方法創建一個日期對象,也可以通過Date.parse()方法將一個字元串轉換為日期對象。

// 創建日期對象
const date1 = new Date('2021-10-16');
const date2 = new Date(2021, 9, 16);

// 字元串轉換為日期對象
const date3 = Date.parse('2021-10-16');

以上代碼中,date1通過字元串創建日期對象,date2通過參數創建日期對象,date3通過字元串轉換為日期對象。

六、JS獲取日期時間

除了獲取日期以外,我們還可以獲取時間,JS中可以通過Date對象的getHours()、getMinutes()和getSeconds()方法獲取小時、分鐘、秒。

const date = new Date();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
const time = `${hour}:${minute}:${second}`;

以上代碼中,getHours()獲取小時,getMinutes()獲取分鐘,getSeconds()獲取秒,構造time字元串。

七、JS獲取日期格式

在JS中,可以通過toLocaleDateString()方法獲取本地化的日期格式。

const date = new Date();
const options = {
  year: 'numeric',
  month: 'long',
  day: 'numeric'
};
const formattedDate = date.toLocaleDateString('zh-CN', options);

以上代碼中,toLocaleDateString()方法返回一個本地化的日期字元串,通過傳入options對象指定日期格式。

八、JS獲取日期時間戳

除了獲取當前日期的時間戳以外,我們還可以通過Date對象的setTime()方法設置時間戳。

const date = new Date();
const timestamp = 1634352646021; // 2021-10-16 15:17:26
date.setTime(timestamp);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const time = `${year}-${month}-${day}`;

以上代碼中,通過setTime()方法設置時間戳,獲取對應的日期年月日。

九、JS獲取日期字元串

除了獲取日期以外,我們還可以將日期對象轉換為字元串,JS中可以通過toLocaleString()方法獲取本地化的日期字元串。

const date = new Date();
const options = {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  timeZone: 'Asia/Shanghai'
};
const dateString = date.toLocaleString('zh-CN', options);

以上代碼中,toLocaleString()方法返回一個本地化的日期時間字元串,通過傳入options對象指定日期時間格式和時區。

原創文章,作者:FAKKL,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/332497.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
FAKKL的頭像FAKKL
上一篇 2025-01-24 18:46
下一篇 2025-01-24 18:46

相關推薦

發表回復

登錄後才能評論