【JavaScript】JavaScript日期和时间的格式化:

news/2024/7/5 2:10:54

文章目录

        • 一、日期和时间的格式化
          • 1、原生方法
          • 2、使用字符串操作方法
          • 3、自定义格式化函数
          • 4、使用第三方库
        • 二、日期和时间的其它常用处理方法
          • 1、创建 Date 对象
          • 2、日期和时间的获取
          • 3、日期和时间的计算
          • 4、日期和时间的比较
          • 5、日期和时间的操作
          • 6、获取上周、本周、上月、本月和本年的开始时间和结束时间
          • 7、根据出生日期计算年龄
          • 8、其他相关的知识点


一、日期和时间的格式化

1、原生方法

【1】使用toLocaleString 方法

//Date 对象有一个 toLocaleString 方法,该方法可以根据本地时间和地区设置格式化日期时间。例如:
//toLocaleString 方法接受两个参数,第一个参数是地区设置,第二个参数是选项,用于指定日期时间格式和时区信息。

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 对象能使日期和时间在特定的语言环境下格式化。可以使用该对象来生成一个格式化日期时间的实例,并根据需要来设置日期时间的格式和时区。例如:
//可以在选项中指定需要的日期时间格式,包括年、月、日、时、分、秒等。同时也可以设置时区信息。

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 的格式。可以根据实际需要来修改格式。
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 等。这些库提供了更多的日期时间格式化选项,并且可以兼容不同的浏览器和环境。
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、创建 Date 对象

要创建一个 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 };
}
//获取时间区间的示例:
//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() 创建 Date 对象时,返回的是当前时区的时间,如果需要使用 UTC 时间,可以使用 new Date(Date.UTC())


http://lihuaxi.xjx100.cn/news/1269731.html

相关文章

OCC-BEV:基于三维场景重建的多摄像机统一预训练

论文&#xff1a;https://arxiv.org/pdf/2305.18829.pdf 代码&#xff1a;https://github.com/chaytonmin/Occ-BEV 多摄像机3D感知技术&#xff08;能够收集车辆周围360的环境信息&#xff09;已经成为自动驾驶领域的一个突出研究领域&#xff0c;为 Lidarb-based 解决方案提供…

【Software Engineering】【期末复习知识点】【2023春】【仅供参考】

文章目录 类型总分占比出勤10%平时作业25%10%期中考试10%期末考试70%附加分提问加分 题型题量分值预测选择152’填空52’名词解释52’软件危机、软件生命周期简答35’综合15’20’15’数据流图、20‘系统流程图、状态转换图、程序流程图、盒图 软件工程期末重点&#xff08;2…

【Springboot集成Neo4j完整版教程】

&#x1f680; Neo4j &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;C…

【VC 7/8】vCenter Server 更新(小版本升级)Ⅱ—— 使用 Shell 命令行更新 vCenter Server

目录 2. 使用 Shell 升级 vCenter Server&#xff08;1&#xff09;下载更新 ISO 镜像&#xff08;2&#xff09;挂载 ISO 镜像&#xff08;3&#xff09;验证 ISO 镜像已被挂载通过VAMI 更新界面将ISO 挂载到 VC 的文件系统 &#xff08;4&#xff09;更新 VC | 安装 vCenter …

nginx主配置文件及实操

文章目录 一、nginx主配置文件nginx.conf1.认识nginx服务的主配置文件2.全局配置3.I/O事件配置4.HTTP配置&#xff15;.检查配置文件是否正确&#xff16;.浏览器测试 二、实战操作1.nginx的访问状态统计2.基于授权的访问控制&#xff1a;3.基于客户端访问设置&#xff08;设置…

短视频矩阵源码开发部署技术解析

短视频矩阵源码开发涉及到多个方面的技术&#xff0c;包括但不限于以下几点&#xff1a; 抖yinAPI&#xff1a;需要通过API获取抖音的视频、用户、评论、点赞等数据。 抖yinSDK&#xff1a;如果需要开发一些原生的功能&#xff0c;比如分享、登录、支付等&#xff0c;需要使用…

lnmp框架的应用

目录 应用一 nginx访问状态统计 1.先查看http_stub_status有没有安装 2.进入nginx的配置文件改配置 3.nginx-检查配置 重启服务 最后这个20就是显示的状态统计 应用二 给网站加密 1.首先安装http-tools软软件 2.把nginx设置锁也要有执行权限 3.进入nginx配置文件 4. 检查…

轻量级的深度学习框架Tinygrad

Tinygrad是一个轻量级的深度学习库&#xff0c;它提供了一种简化和直观的方法来理解和实现神经网络。在本文中&#xff0c;我们将探讨Tinygrad及其主要功能&#xff0c;以及它如何成为那些开始深度学习之旅的人的有价值的工具。 什么是Tinygrad? Tinygrad是一个开源的深度学习…