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

JavaScript?Date對象之獲取日期、時間與年份完全指南

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

一、Date 對象基礎

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

創(chuàng)建 Date 實例

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

// 2. 通過時間戳創(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開始計數(shù)的(0=一月,11=十二月)
const specificDate = new Date(2023, 9, 20, 14, 30, 0);

二、獲取當前日期和時間

1. 獲取完整日期時間字符串

const now = new Date();

// 1. 本地日期時間字符串
console.log(now.toString()); 
// 示例輸出: "Fri Oct 20 2023 14:30:45 GMT+0800 (中國標準時間)"

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

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

// 4. 本地時間字符串
console.log(now.toTimeString()); 
// 示例輸出: "14:30:45 GMT+0800 (中國標準時間)"

// 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. 獲取各個日期時間組件

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 (表示星期五)

// 獲取小時(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

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

三、獲取當前年份的多種方式

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)

四、日期格式化實用技巧

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. 相對時間顯示

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)}小時前`;
  
  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小時前"
console.log(timeAgo(new Date(2023, 9, 1))); // "2023-10-01"

五、時區(qū)處理

1. 獲取UTC時間

const now = new Date();

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

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

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

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

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

六、日期計算

1. 日期加減

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

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

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

2. 計算日期差

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天

七、最佳實踐與注意事項

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

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

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

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

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

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

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

1. Temporal提案(未來標準)

// 提案階段,未來可能的標準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對象提供了豐富的API來處理日期和時間:

  • 獲取當前日期時間new Date()

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

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

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

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

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

相關文章

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    BootStrap 附加導航組件

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

最新評論