欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript?Date對(duì)象之獲取日期、時(shí)間與年份完全指南

 更新時(shí)間:2025年08月29日 09:15:56   作者:椰子女士的面條  
Date對(duì)象是JavaScript中的一個(gè)核心內(nèi)置對(duì)象,它允許我們創(chuàng)建、操作和格式化日期和時(shí)間,這篇文章主要介紹了JavaScript?Date對(duì)象之獲取日期、時(shí)間與年份的相關(guān)資料,需要的朋友可以參考下

一、Date 對(duì)象基礎(chǔ)

JavaScript 的 Date 對(duì)象是處理日期和時(shí)間的內(nèi)置對(duì)象,它可以表示從 1970 年 1 月 1 日 UTC(協(xié)調(diào)世界時(shí))至今的毫秒數(shù)。

創(chuàng)建 Date 實(shí)例

// 1. 獲取當(dāng)前日期和時(shí)間
const now = new Date();

// 2. 通過時(shí)間戳創(chuàng)建
const timestamp = 1634567890123; // 毫秒數(shù)
const dateFromTimestamp = new Date(timestamp);

// 3. 通過日期字符串創(chuàng)建
const dateFromString = new Date("2023-10-20T14:30:00");

// 4. 通過年、月、日等參數(shù)創(chuàng)建
// 注意:月份是從0開始計(jì)數(shù)的(0=一月,11=十二月)
const specificDate = new Date(2023, 9, 20, 14, 30, 0);

二、獲取當(dāng)前日期和時(shí)間

1. 獲取完整日期時(shí)間字符串

const now = new Date();

// 1. 本地日期時(shí)間字符串
console.log(now.toString()); 
// 示例輸出: "Fri Oct 20 2023 14:30:45 GMT+0800 (中國(guó)標(biāo)準(zhǔn)時(shí)間)"

// 2. ISO 格式字符串
console.log(now.toISOString()); 
// 示例輸出: "2023-10-20T06:30:45.000Z"

// 3. 本地日期字符串
console.log(now.toDateString()); 
// 示例輸出: "Fri Oct 20 2023"

// 4. 本地時(shí)間字符串
console.log(now.toTimeString()); 
// 示例輸出: "14:30:45 GMT+0800 (中國(guó)標(biāo)準(zhǔn)時(shí)間)"

// 5. 本地化格式
console.log(now.toLocaleString()); 
// 示例輸出: "2023/10/20 14:30:45"
console.log(now.toLocaleDateString()); 
// 示例輸出: "2023/10/20"
console.log(now.toLocaleTimeString()); 
// 示例輸出: "14:30:45"

2. 獲取各個(gè)日期時(shí)間組件

const now = new Date();

// 獲取年份(4位數(shù))
const fullYear = now.getFullYear(); // 2023

// 獲取月份(0-11)
const month = now.getMonth(); // 9 (表示十月)

// 獲取日期(1-31)
const date = now.getDate(); // 20

// 獲取星期(0-6,0表示星期日)
const day = now.getDay(); // 5 (表示星期五)

// 獲取小時(shí)(0-23)
const hours = now.getHours(); // 14

// 獲取分鐘(0-59)
const minutes = now.getMinutes(); // 30

// 獲取秒數(shù)(0-59)
const seconds = now.getSeconds(); // 45

// 獲取毫秒(0-999)
const milliseconds = now.getMilliseconds(); // 0

// 獲取時(shí)間戳(自1970年1月1日以來的毫秒數(shù))
const timestamp = now.getTime(); // 1697783445000

三、獲取當(dāng)前年份的多種方式

1. 基本方法

const currentYear = new Date().getFullYear();
console.log(currentYear); // 2023

2. 其他獲取年份的方法

const now = new Date();

// 方法1: getFullYear() (推薦)
const year1 = now.getFullYear(); // 2023

// 方法2: 從ISO字符串中提取
const year2 = now.toISOString().slice(0, 4); // "2023"

// 方法3: 使用Intl.DateTimeFormat
const year3 = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(now); // "2023"

// 方法4: 從本地化字符串中提取
const year4 = now.toLocaleDateString('zh-CN', { year: 'numeric' }); // "2023"

// 不推薦的方法: getYear() (已廢棄)
const yearOld = now.getYear(); // 123 (2023-1900)

四、日期格式化實(shí)用技巧

1. 自定義格式化函數(shù)

function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  return `${year}-${month}-${day}`;
}

console.log(formatDate(new Date())); // "2023-10-20"

2. 格式化為更易讀的形式

function formatNiceDate(date) {
  const months = ['一月', '二月', '三月', '四月', '五月', '六月', 
                 '七月', '八月', '九月', '十月', '十一月', '十二月'];
  
  return `${date.getFullYear()}年 ${months[date.getMonth()]} ${date.getDate()}日`;
}

console.log(formatNiceDate(new Date())); // "2023年 十月 20日"

3. 相對(duì)時(shí)間顯示

function timeAgo(date) {
  const now = new Date();
  const seconds = Math.floor((now - date) / 1000);
  
  if (seconds < 60) return `${seconds}秒前`;
  if (seconds < 3600) return `${Math.floor(seconds/60)}分鐘前`;
  if (seconds < 86400) return `${Math.floor(seconds/3600)}小時(shí)前`;
  
  const days = Math.floor(seconds/86400);
  return days < 30 ? `${days}天前` : formatDate(date);
}

console.log(timeAgo(new Date(Date.now() - 5000))); // "5秒前"
console.log(timeAgo(new Date(Date.now() - 3600000))); // "1小時(shí)前"
console.log(timeAgo(new Date(2023, 9, 1))); // "2023-10-01"

五、時(shí)區(qū)處理

1. 獲取UTC時(shí)間

const now = new Date();

// 獲取UTC時(shí)間組件
const utcHours = now.getUTCHours();
const utcMinutes = now.getUTCMinutes();

// 轉(zhuǎn)換為UTC字符串
console.log(now.toUTCString()); 
// "Fri, 20 Oct 2023 06:30:45 GMT"

2. 時(shí)區(qū)轉(zhuǎn)換

function convertTimezone(date, timezone) {
  return new Date(date.toLocaleString('en-US', { timeZone: timezone }));
}

// 將當(dāng)前時(shí)間轉(zhuǎn)換為紐約時(shí)間
const nyTime = convertTimezone(new Date(), 'America/New_York');
console.log(nyTime.toLocaleString()); 
// "10/20/2023, 2:30:45 AM" (假設(shè)北京時(shí)間是14:30)

六、日期計(jì)算

1. 日期加減

// 加5天
const date = new Date();
date.setDate(date.getDate() + 5);

// 減3個(gè)月
date.setMonth(date.getMonth() - 3);

// 加2年
date.setFullYear(date.getFullYear() + 2);

2. 計(jì)算日期差

function dateDiffInDays(date1, date2) {
  const diffTime = Math.abs(date2 - date1);
  return Math.floor(diffTime / (1000 * 60 * 60 * 24)); 
}

const start = new Date(2023, 0, 1); // 2023年1月1日
const end = new Date(2023, 9, 20); // 2023年10月20日
console.log(dateDiffInDays(start, end)); // 292天

七、最佳實(shí)踐與注意事項(xiàng)

  • 月份從0開始:一月是0,十二月是11

  • 使用getFullYear():不要使用已廢棄的getYear()

  • 處理時(shí)區(qū)問題:明確業(yè)務(wù)是否需要考慮時(shí)區(qū)

  • 日期不可變性:進(jìn)行日期計(jì)算時(shí)最好創(chuàng)建新對(duì)象

    // 推薦做法
    const newDate = new Date(oldDate.getTime());
    newDate.setDate(newDate.getDate() + 1);
    
    // 不推薦 - 修改了原對(duì)象
    oldDate.setDate(oldDate.getDate() + 1);
  • 性能考慮:頻繁創(chuàng)建Date對(duì)象會(huì)影響性能

  • 使用庫處理復(fù)雜邏輯:考慮使用moment.js、date-fns等庫處理復(fù)雜日期操作

八、現(xiàn)代JavaScript日期處理

1. Temporal提案(未來標(biāo)準(zhǔn))

// 提案階段,未來可能的標(biāo)準(zhǔn)API
const today = Temporal.Now.plainDateISO();
console.log(today.year); // 2023
console.log(today.month); // 10 (不再是0-based)
console.log(today.day); // 20

2. 使用第三方庫

// 使用date-fns庫示例
import { format, addDays, differenceInDays } from 'date-fns';

const today = new Date();
console.log(format(today, 'yyyy-MM-dd')); // "2023-10-20"

const tomorrow = addDays(today, 1);
console.log(differenceInDays(tomorrow, today)); // 1

總結(jié)

JavaScript的Date對(duì)象提供了豐富的API來處理日期和時(shí)間:

  • 獲取當(dāng)前日期時(shí)間new Date()

  • 獲取年份getFullYear()(推薦)

  • 獲取日期組件getDate()getMonth()getHours()

  • 格式化顯示toLocaleString()toISOString()等方法

  • 日期計(jì)算:通過setDate()setFullYear()等方法進(jìn)行

記住處理日期時(shí)的常見陷阱(如月份從0開始),對(duì)于復(fù)雜場(chǎng)景可以考慮使用專門的日期庫。隨著Temporal提案的推進(jìn),未來JavaScript的日期處理將變得更加簡(jiǎn)單和強(qiáng)大。

相關(guān)文章

  • JavaScript分支語句和循環(huán)語句示例詳解

    JavaScript分支語句和循環(huán)語句示例詳解

    JavaScript作為一種廣泛使用的編程語言,它的流程控制語句是構(gòu)建邏輯和實(shí)現(xiàn)功能的基礎(chǔ),這篇文章主要介紹了JavaScript分支語句和循環(huán)語句的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2025-08-08
  • js回調(diào)函數(shù)原理與用法案例分析

    js回調(diào)函數(shù)原理與用法案例分析

    這篇文章主要介紹了js回調(diào)函數(shù)原理與用法,結(jié)合具體案例形式分析了js回調(diào)函數(shù)基本概念、原理、使用方法及操作注意事項(xiàng),需要的朋友可以參考下
    2020-03-03
  • JavaScript字符串常用類使用方法匯總

    JavaScript字符串常用類使用方法匯總

    今天的這篇文章就分享幾年以來總結(jié)的一些最常見和最有用的字符串相關(guān)的方法的例子和簡(jiǎn)要說明。便于程序員用于快速參考。當(dāng)然,最有經(jīng)驗(yàn)的開發(fā)人員對(duì)這些操作很熟悉,但我認(rèn)為這是一個(gè)很好的方法幫助初學(xué)者理解這些函數(shù),他可以幫助你使用簡(jiǎn)單的語法,完成復(fù)雜的操作.
    2015-04-04
  • javascrit中undefined和null的區(qū)別詳解

    javascrit中undefined和null的區(qū)別詳解

    這篇文章主要介紹了javascrit中undefined和null的區(qū)別詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-04-04
  • JavaScript實(shí)現(xiàn)簡(jiǎn)單Tip提示框效果

    JavaScript實(shí)現(xiàn)簡(jiǎn)單Tip提示框效果

    這篇文章主要介紹了JavaScript實(shí)現(xiàn)簡(jiǎn)單Tip提示框效果,涉及JavaScript響應(yīng)鼠標(biāo)事件針對(duì)頁面元素動(dòng)態(tài)操作的相關(guān)技巧,需要的朋友可以參考下
    2016-04-04
  • javascript實(shí)現(xiàn)拼圖游戲

    javascript實(shí)現(xiàn)拼圖游戲

    這篇文章主要為大家詳細(xì)介紹了javascript實(shí)現(xiàn)拼圖游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-01-01
  • 純javascript實(shí)現(xiàn)選擇框的全選與反選功能

    純javascript實(shí)現(xiàn)選擇框的全選與反選功能

    這篇文章主要介紹了純javascript實(shí)現(xiàn)選擇框的全選與反選 ,需要的朋友可以參考下
    2019-04-04
  • JavaScript實(shí)現(xiàn)經(jīng)緯度轉(zhuǎn)換常用方法總結(jié)

    JavaScript實(shí)現(xiàn)經(jīng)緯度轉(zhuǎn)換常用方法總結(jié)

    WGS84坐標(biāo)系、GCJ02坐標(biāo)系、BD09坐標(biāo)系和Web 墨卡托投影坐標(biāo)系是我們常見的四個(gè)坐標(biāo)系。這篇文章為大家整理了這四個(gè)坐標(biāo)系之間相互轉(zhuǎn)換的方法,需要的可以參考一下
    2023-02-02
  • js跳轉(zhuǎn)到指定url的方法與實(shí)際使用

    js跳轉(zhuǎn)到指定url的方法與實(shí)際使用

    這篇文章主要給大家介紹了關(guān)于js跳轉(zhuǎn)到指定url的方法與實(shí)際使用的相關(guān)資料,要實(shí)現(xiàn)JavaScript跳轉(zhuǎn)到指定URL,可以使用window.location對(duì)象來實(shí)現(xiàn),需要的朋友可以參考下
    2023-09-09
  • BootStrap 附加導(dǎo)航組件

    BootStrap 附加導(dǎo)航組件

    Bootstrap 是一個(gè)用于快速開發(fā) Web 應(yīng)用程序和網(wǎng)站的前端框架,主要基于 HTML、CSS、JAVASCRIPT 的。接下來通過本文給大家介紹BootStrap 附加導(dǎo)航組件的知識(shí),感興趣的朋友一起學(xué)習(xí)吧
    2016-07-07

最新評(píng)論