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

JavaScript日期和時間的格式化及其它常用處理方法

 更新時間:2023年09月04日 11:12:53   作者:Sun?Peng  
這篇文章主要給大家介紹了關于JavaScript日期和時間的格式化及其它常用處理方法,JavaScript中可以使用Date對象來表示日期和時間,如果需要格式化日期和時間,可以使用Date對象的幾個方法和一些字符串操作方法來實現,需要的朋友可以參考下

一、日期和時間的格式化

1、原生方法

【1】使用toLocaleString 方法

//Date 對象有一個 toLocaleString 方法,該方法可以根據本地時間和地區(qū)設置格式化日期時間。例如:
//toLocaleString 方法接受兩個參數,第一個參數是地區(qū)設置,第二個參數是選項,用于指定日期時間格式和時區(qū)信息。
const date = new Date();
console.log(date.toLocaleString('en-US', { timeZone: 'America/New_York' })); // 2/16/2023, 8:25:05 AM
console.log(date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })); // 2023/2/16 上午8:25:05

【2】使用 Intl.DateTimeFormat 對象

//Intl.DateTimeFormat 對象能使日期和時間在特定的語言環(huán)境下格式化??梢允褂迷搶ο髞砩梢粋€格式化日期時間的實例,并根據需要來設置日期時間的格式和時區(qū)。例如:
//可以在選項中指定需要的日期時間格式,包括年、月、日、時、分、秒等。同時也可以設置時區(qū)信息。
const date = new Date();
const formatter = new Intl.DateTimeFormat('en-US', {
  timeZone: 'America/New_York',
  year: 'numeric',
  month: 'numeric',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
});
console.log(formatter.format(date)); // 2/19/2023, 9:17:40 AM
const dateCN = new Date();
const formatterCN = new Intl.DateTimeFormat('zh-CN', {
  timeZone: 'Asia/Shanghai',
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
});
console.log(formatterCN.format(dateCN)); // 2023/02/19 22:17:40

2、使用字符串操作方法

//可以使用字符串操作方法來將日期時間格式化為特定格式的字符串。例如:
const date = new Date();
const year = date.getFullYear().toString().padStart(4, '0');
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hour = date.getHours().toString().padStart(2, '0');
const minute = date.getMinutes().toString().padStart(2, '0');
const second = date.getSeconds().toString().padStart(2, '0');
console.log(`${year}-${month}-${day} ${hour}:${minute}:${second}`); // 2023-02-16 08:25:05
//以上代碼使用了字符串模板和字符串操作方法,將日期時間格式化為 YYYY-MM-DD HH:mm:ss 的格式??梢愿鶕嶋H需要來修改格式。

3、自定義格式化函數

【1】不可指定格式的格式化函數

//可以編寫自定義函數來格式化日期時間。例如:
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return `${year}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`;
}
function pad(num) { return num.toString().padStart(2, '0')}
const date = new Date();
console.log(formatDateTime(date)); // 2023-02-16 08:25:05
//以上代碼定義了一個 formatDateTime 函數和一個 pad 函數,用于格式化日期時間并補齊數字。可以根據需要修改格式,因此通用性較低。

【2】可指定格式的格式化函數

//下面是一個通用較高的自定義日期時間格式化函數的示例:
function formatDateTime(date, format) {
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小時
    'H+': date.getHours(), // 小時
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
    a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
    A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      );
    }
  }
  return format;
}
//這個函數接受兩個參數,第一個參數是要格式化的日期時間,可以是 Date 對象或表示日期時間的字符串,第二個參數是要格式化的格式,例如 yyyy-MM-dd HH:mm:ss。該函數會將日期時間格式化為指定的格式,并返回格式化后的字符串。
//該函數使用了正則表達式來匹配格式字符串中的占位符,然后根據對應的日期時間值來替換占位符。其中,y 會被替換為年份,M、d、h、H、m、s、q、S、a、A 分別表示月份、日期、小時(12 小時制)、小時(24 小時制)、分鐘、秒、季度、毫秒、上午/下午、AM/PM。
//使用該函數進行日期時間格式化的示例如下:
const date = new Date();
console.log(formatDateTime(date, 'yyyy-MM-dd HH:mm:ss')); // 2023-02-16 08:25:05
console.log(formatDateTime(date, 'yyyy年MM月dd日 HH:mm:ss')); // 2023年02月16日 08:25:05
console.log(formatDateTime(date, 'yyyy-MM-dd HH:mm:ss S')); // 2023-02-16 08:25:05 950
console.log(formatDateTime(date, 'yyyy-MM-dd hh:mm:ss A')); // 2023-02-16 08:25:05 上午
//可以根據實際需要修改格式化的格式,以及支持更多的占位符和格式化選項。

4、使用第三方庫

//除了原生的方法外,還有很多第三方庫可以用來格式化日期時間,例如 Moment.js 和 date-fns 等。這些庫提供了更多的日期時間格式化選項,并且可以兼容不同的瀏覽器和環(huán)境。
const date = new Date();
console.log(moment(date).format('YYYY-MM-DD HH:mm:ss')); // 2023-02-16 08:25:05
console.log(dateFns.format(date, 'yyyy-MM-dd HH:mm:ss')); // 2023-02-16 08:25:05
//以上是幾種常用的日期時間格式化方法,在進行日期時間格式化時,可以使用原生的方法、自定義函數或第三方庫,選擇合適的方法根據實際需要進行格式化。

二、日期和時間的其它常用處理方法

1、創(chuàng)建 Date 對象

要創(chuàng)建一個 Date 對象,可以使用 new Date(),不傳入任何參數則會使用當前時間。也可以傳入一個日期字符串或毫秒數,例如:

const now = new Date(); // 當前時間
const date1 = new Date("2022-01-01"); // 指定日期字符串
const date2 = new Date(1640995200000); // 指定毫秒數

2、日期和時間的獲取

Date 對象可以通過許多方法獲取日期和時間的各個部分,例如:

const date = new Date();
const year = date.getFullYear(); // 年份,例如 2023
const month = date.getMonth(); // 月份,0-11,0 表示一月,11 表示十二月
const day = date.getDate(); // 日期,1-31
const hour = date.getHours(); // 小時,0-23
const minute = date.getMinutes(); // 分鐘,0-59
const second = date.getSeconds(); // 秒數,0-59
const millisecond = date.getMilliseconds(); // 毫秒數,0-999
const weekday = date.getDay(); // 星期幾,0-6,0 表示周日,6 表示周六

3、日期和時間的計算

?可以使用 Date 對象的 set 方法來設置日期和時間的各個部分,也可以使用 get 方法獲取日期和時間的各個部分,然后進行計算。例如,要計算兩個日期之間的天數,可以先將兩個日期轉換成毫秒數,然后計算它們之間的差值,最后將差值轉換成天數,例如:

const date1 = new Date("2022-01-01");
const date2 = new Date("2023-02-16");
const diff = date2.getTime() - date1.getTime(); // 毫秒數
const days = diff / (1000 * 60 * 60 * 24); // 天數

4、日期和時間的比較

可以使用 Date 對象的 getTime() 方法將日期轉換成毫秒數,然后比較兩個日期的毫秒數大小,以確定它們的順序。例如,要比較兩個日期的先后順序,可以將它們轉換成毫秒數,然后比較它們的大小,例如:

const date1 = new Date("2022-01-01");
const date2 = new Date("2023-02-16");
if (date1.getTime() < date2.getTime()) {
  console.log("date1 在 date2 之前");
} else if (date1.getTime() > date2.getTime()) {
  console.log("date1 在 date2 之后");
} else {
  console.log("date1 和 date2 相等");
}

5、日期和時間的操作

可以使用 Date 對象的一些方法來進行日期和時間的操作,例如,使用 setDate() 方法設置日期,使用 setHours() 方法設置小時數,使用 setTime() 方法設置毫秒數等等。例如,要將日期增加一天,可以使用 setDate() 方法,例如:

const date = new Date();
date.setDate(date.getDate() + 1); // 增加一天
console.log(date.toLocaleDateString()); // 輸出增加一天后的日期

6、獲取上周、本周、上月、本月和本年的開始時間和結束時間

// 獲取本周的開始時間和結束時間
function getThisWeek() {
  const now = new Date();
  const day = now.getDay() === 0 ? 7 : now.getDay(); // 將周日轉換為 7
  const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day + 1);
  const weekEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (6 - day) + 1);
  return { start: weekStart, end: weekEnd };
}
//獲取時間區(qū)間的示例:
//const thisWeek = getThisWeek();
//console.log(thisWeek.start); // 本周的開始時間
//console.log(thisWeek.end); // 本周的結束時間
// 獲取上周的開始時間和結束時間
function getLastWeek() {
  const now = new Date();
  const day = now.getDay() === 0 ? 7 : now.getDay(); // 將周日轉換為 7
  const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day - 6);
  const weekEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day);
  return { start: weekStart, end: weekEnd };
}
// 獲取本月的開始時間和結束時間
function getThisMonth() {
  const now = new Date();
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
  return { start: monthStart, end: monthEnd };
}
// 獲取上月的開始時間和結束時間
function getLastMonth() {
  const now = new Date();
  const monthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  const monthEnd = new Date(now.getFullYear(), now.getMonth(), 0);
  return { start: monthStart, end: monthEnd };
}
// 獲取本年的開始時間和結束時間
function getThisYear() {
  const now = new Date();
  const yearStart = new Date(now.getFullYear(), 0, 1);
  const yearEnd = new Date(now.getFullYear(), 11, 31);
  return { start: yearStart, end: yearEnd };
}

7、根據出生日期計算年齡

function calculateAge(birthDate) {
  const birthYear = birthDate.getFullYear();
  const birthMonth = birthDate.getMonth();
  const birthDay = birthDate.getDate();
  const now = new Date();
  let age = now.getFullYear() - birthYear;
  if (now.getMonth() < birthMonth || (now.getMonth() === birthMonth && now.getDate() < birthDay)) {
    age--;
  }
  // 檢查閏年
  const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  const isBirthLeapYear = isLeapYear(birthYear);
  // 調整閏年的年齡
  if (isBirthLeapYear && birthMonth > 1) {
    age--;
  }
  if (isLeapYear(now.getFullYear()) && now.getMonth() < 1) {
    age--;
  }
  return age;
}
//使用這個函數計算年齡的示例:
//const birthDate = new Date("1990-01-01");
//const age = calculateAge(birthDate);
//console.log(age); // 33

8、其他相關的知識點

在使用 Date 對象時,需要注意以下幾點:
(1)月份從 0 開始,0 表示一月,11 表示十二月;
(2)getDate() 方法返回的是日期,而 getDay() 方法返回的是星期幾;
(3)Date 對象的年份是完整的四位數,例如 2023;
(4)使用 new Date() 創(chuàng)建 Date 對象時,返回的是當前時區(qū)的時間,如果需要使用 UTC 時間,可以使用 new Date(Date.UTC())

總結 

到此這篇關于JavaScript日期和時間的格式化及其它常用處理方法的文章就介紹到這了,更多相關JS日期和時間格式化內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論