一、日期和时间的格式化

1、原生方法

1.1、使用 toLocaleString 方法

Date 对象有一个 toLocaleString 方法,该方法可以根据本地时间和地区设置格式化日期时间。例如:

const date = new Date();
console.log(date.toLocaleString('en-US', { timeZone: 'America/New_York' })); // 2/18/2023, 21:49:05 AM
console.log(date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })); // 2023/2/18 晚上9:49:05

toLocaleString 方法接受两个参数,第一个参数是地区设置,第二个参数是选项,用于指定日期时间格式和时区信息。

1.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/18/2023, 9:49:05 PM

可以在选项中指定需要的日期时间格式,包括年、月、日、时、分、秒等。同时也可以设置时区信息。

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-18 21:49:05

以上代码使用了字符串模板和字符串操作方法,将日期时间格式化为 YYYY-MM-DD HH:mm:ss 的格式。可以根据实际需要来修改格式。

3、自定义格式化函数

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-18 21:49:05

以上代码定义了一个 formatDateTime 函数和一个 pad 函数,用于格式化日期时间并补齐数字。可以根据需要修改格式,因此通用性较低

3.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-18 21:49:05
console.log(formatDateTime(date, 'yyyy年MM月dd日 HH:mm:ss')); // 2023年02月18日 21:49:05
console.log(formatDateTime(date, 'yyyy-MM-dd HH:mm:ss S')); // 2023-02-18 21:49:05 950
console.log(formatDateTime(date, 'yyyy-MM-dd hh:mm:ss A')); // 2023-02-18 21:49:05 下午

可以根据实际需要修改格式化的格式,以及支持更多的占位符和格式化选项。

4、使用第三方库

除了原生的方法外,还有很多第三方库可以用来格式化日期时间,例如 Moment.js 和 date-fns 等。这些库提供了更多的日期时间格式化选项,并且可以兼容不同的浏览器和环境

const date = new Date();
console.log(moment(date).format('YYYY-MM-DD HH:mm:ss')); // 2023-02-18 21:49:05
console.log(dateFns.format(date, 'yyyy-MM-dd HH:mm:ss')); // 2023-02-18 21:49:05

以上是几种常用的日期时间格式化方法,在进行日期时间格式化时,可以使用原生的方法、自定义函数或第三方库,选择合适的方法根据实际需要进行格式化。

二、日期和时间的其它常用处理方法

1、创建 Date 对象

要创建一个 Date 对象,可以使用 new Date(),不传入任何参数则会使用当前时间。也可以传入一个日期字符串或毫秒数,例如:

const now = new Date(); // 当前时间
const date1 = new Date("2023-2-18"); // 指定日期字符串
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-02-01");
const date2 = new Date("2023-02-18");
const diff = date2.getTime() - date1.getTime(); // 毫秒数
const days = diff / (1000 * 60 * 60 * 24); // 天数

4、日期和时间的比较

可以使用 Date 对象的 getTime() 方法将日期转换成毫秒数,然后比较两个日期的毫秒数大小,以确定它们的顺序。例如,要比较两个日期的先后顺序,可以将它们转换成毫秒数,然后比较它们的大小,例如:

const date1 = new Date("2022-02-02");
const date2 = new Date("2023-02-18");
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、获取上周、本周、上月和本月的开始时间和结束时间

以下是 JavaScript 获取本周、上周、本月和上月的开始时间和结束时间的代码示例:

// 获取本周的开始时间和结束时间
function getThisWeek() {const now = new Date();const day = now.getDay() === 0 ? 7 : now.getDay(); // 将周日转换为 7const 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 };
}// 获取上周的开始时间和结束时间
function getLastWeek() {const now = new Date();const day = now.getDay() === 0 ? 7 : now.getDay(); // 将周日转换为 7const 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 };
}

上述代码中,getThisWeek()、getLastWeek()、getThisMonth() 和 getLastMonth() 函数分别返回当前时间所在的本周、上周、本月和上月的开始时间和结束时间。这些函数使用了 Date 对象的方法,例如 getFullYear()、getMonth() 和 getDate() 等。它们可以用于获取需要进行时间区间计算的场景,例如统计某个时间范围内的数据等。

使用这些函数获取时间区间的示例:

const thisWeek = getThisWeek();
console.log(thisWeek.start); // 本周的开始时间
console.log(thisWeek.end); // 本周的结束时间const lastWeek = getLastWeek();
console.log(lastWeek.start); // 上周的开始时间
console.log(lastWeek.end); // 上周的结束时间const thisMonth = getThisMonth();
console.log(thisMonth.start); // 本月的开始时间
console.log(thisMonth.end); // 本月的结束时间const lastMonth = getLastMonth();
console.log(lastMonth.start); // 上月的开始时间
console.log(lastMonth.end); // 上月的结束时间

使用这些函数可以方便地获取需要的时间区间,并进行后续的操作。

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;
}

这个函数接收一个 Date 对象作为参数,代表出生日期。该函数计算当前日期与出生日期之间的时间差,以确定年龄。其中,使用 Date 对象的 getFullYear()、getMonth() 和 getDate() 方法获取出生日期的年、月和日。使用当前日期的年、月和日计算出年龄。如果当前月份小于出生月份,或当前月份等于出生月份但当前日期小于出生日期,则年龄减一。在这个函数中,定义了一个 isLeapYear() 函数,用于检查给定的年份是否为闰年。然后,在计算年龄时,调用这个函数,检查出生年份和当前年份是否为闰年。如果出生年份为闰年且出生月份在二月或之后,则年龄减一。如果当前年份为闰年且当前月份在一月或之前,则年龄减一。这样,就可以正确计算含有闰年的出生日期的年龄了。

这种计算年龄的方法仅是基于当前日期和出生日期之间的时间差,而不是考虑具体的月份和日期。因此,对于生日还未到的人,计算的年龄会比实际年龄小一岁。

使用这个函数计算年龄的示例:

const birthDate = new Date("2000-01-01");
const age = calculateAge(birthDate);
console.log(age); // 33

上述代码中,构造了一个 Date 对象,它代表出生日期。然后调用 calculateAge() 函数,将出生日期作为参数传入。该函数返回当前日期与出生日期之间的时间差,以确定年龄。最后打印计算出的年龄。

8、其他相关的知识点

在使用 Date 对象时,需要注意以下几点:

  • 月份从 0 开始,0 表示一月,11 表示十二月;
  • getDate() 方法返回的是日期,而 getDay() 方法返回的是星期几;
  • Date 对象的年份是完整的四位数,例如 2023;
  • 使用 new Date() 创建 Date 对象时,返回的是当前时区的时间,如果需要使用 UTC 时间,可以使用 new Date(Date.UTC())。

JavaScript 中的 Date 对象提供了许多方法和属性,可以用于处理日期和时间,根据具体情况选择适合的方法和技巧。

JavaScript 日期和时间的格式化大汇总(收集)相关推荐

  1. C#日期时间类型格式化大全集 C#DateTime 类型格式化大全集

    日期转化一 为了达到不同的显示效果有时,我们须要对时间进行转化,默认格式为:2007-01-03 14:33:34 ,要转化为其它格式,要用到DateTime.ToString的方法(String, ...

  2. JavaScript Date() setDate() 时间的格式化 加一天 减一天

    JavaScript Date() 时间的格式化与日期的增加减少 格式化时间显示格式 let newDateFun = function(date) {let date = new Date(date ...

  3. java格式化日期时分秒_Java 日期、时间类,日期、时间的格式化

    Java提供了Date.Calendar两个类用于处理日期.时间. 但Date的大部分构造器.方法已经过时,不在推荐使用,Calendar类又过于复杂,所以Java8推出了一套新的时间日期库. 1.D ...

  4. 日期和时间的格式化定义(ISO C89)

    格式化定义本质上控制的是占位. 日期 %Y:4位数的年份: %y:2位数的年份: %m:2位数的月份(1-12) %d:2位数的日(01-31) 时间 %H:24小时制(0-23) %I:12小时制( ...

  5. JavaScript 日期与时间转换

    1. 获取当前日期 使用实例:getnowDate('-'); getnowDate('.'); 结果实例:'2022-09-09'; '2022.09.09' /*** 获取当前日期* {param ...

  6. python中日期和时间格式化输出的方法

    1.将字符串的时间转换为时间戳 方法: a = "2013-10-10 23:40:00" #将其转换为时间数组 import time timeArray = time.strp ...

  7. [转载] python中日期和时间格式化输出的方法

    参考链接: Python程序将时间从12小时转换为24小时格式 1.将字符串的时间转换为时间戳 方法: a = "2013-10-10 23:40:00" #将其转换为时间数组 i ...

  8. Java_格式化日期和时间

    1.常用日期和时间的格式化转换符 import java.util.Date;public class DateFormatTest {public static void main(String[] ...

  9. python中处理日期和时间的标准模块是-datetime

    datetime是Python处理日期和时间的标准库. 获取当前日期和时间 我们先看如何获取当前日期和时间: >>> from datetime import datetime &g ...

最新文章

  1. 陆奇全面解读 AI 创业创新发展趋势,创业公司应该如何把握住机会?
  2. python自带的shell是什么-python的shell是什么
  3. BFS求无权图的单源最短路径-邻接矩阵存储
  4. Android插件化原理解析——广播的管理
  5. review_core_basic_java(1)java程序设计概述
  6. ajax请求解析json,如何为Ajax请求解析json响应?
  7. 架构师的职责都有哪些?
  8. 微信自动截取PPT或者黑/白版图片
  9. 单元测试(一)使用Junit进行单元测试
  10. 机器人学笔记之——空间描述和变换:位置、姿态与坐标系
  11. CodeForces - 1040B Shashlik Cooking (思维/贪心)
  12. python下载图片到文件夹_Python批量下载网页图片详细教程
  13. Windows10正式版为什么没有休眠选项?
  14. CSR蓝牙遥控器OTA固件升级
  15. esxi6.5磁盘格式转换
  16. 钉钉自定义机器人日志报警
  17. 您的captcha验证码设置对了吗?
  18. python外星人颜色答案_Python-外星人
  19. ukey的密码学原理
  20. 厂房规划物流仿真之sketchUP(SU)

热门文章

  1. 有哪些能支持epub、txt格式的电子书阅读器?在win10上用的?
  2. HTML清除浮动的四种方式
  3. Android 11.0 SystemUI导航栏固定在底部显示的修改
  4. 定积分之积分上限函数分段问题
  5. pda扫描枪屏幕_pda扫描器与条码扫描枪的区别是什么?
  6. ArcGIS水文分析提取河网及流域
  7. 更改Git 服务器 IP 地址并更新Git项目
  8. python动态横道图_用Python pyecharts v1.x 绘制图形【转】
  9. CAD/CAM/CAE基础(三) 材料加工CAE技术基础
  10. rewrite 防止迅雷下载