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

这篇具有很好参考价值的文章主要介绍了【JavaScript】JavaScript日期和时间的格式化:。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


一、日期和时间的格式化
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())文章来源地址https://www.toymoban.com/news/detail-685612.html

到了这里,关于【JavaScript】JavaScript日期和时间的格式化:的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • js实现日期格式化

    获取到的是1970年1月1日至今的毫秒数 月份从0开始的所以要加1 实现日期格式化效果图 日期格式化实现效果图 其中包含封装一个不够两位数就补零的函数 一个不够两位数就补零的函数

    2024年02月13日
    浏览(43)
  • JavaScript 格式化金额

    这是 JavaScript 中格式化金额的最常见方法。 Intl.NumberFormat() 构造函数接受两个参数:语言环境和选项。语言环境是为其格式化金额的语言和地区。选项是一组控制金额格式的属性。例如,可以使用样式属性来指定货币的格式,使用货币属性来指定要将金额格式化为的货币。

    2024年02月06日
    浏览(32)
  • Java8日期时间类LocalDateTime格式化

    LocalDateTime日期时间格式化 LocalDateTime localDateTime = LocalDateTime.now() System.out.println(now.format( DateTimeFormatter.ofPattern(\\\"yyyy-MM-dd HH:mm:ss\\\") )); 测试1 测试2 测试2的结果

    2024年02月08日
    浏览(37)
  • Windows bat 批处理 日期时间格式化

    有一个批处理脚本,脚本中根据当前日期,动态的生成日志文件, 如:当前是 2023年06月20日,我希望生成的日志文件名为:XX_20230620.log Windows 在批处理中 获取日期和时间的方式如下: echo %time% 输出的时间格式: HH:MM:SS.NN HH :时 MM :分 SS :秒 NN :厘秒(注意不是毫秒,1秒

    2024年02月11日
    浏览(55)
  • sqlite3日期时间格式化和自动输入

    Sqlite3系列:初步💎where💎select sqlite中并未提供单独的日期时间类型,但提供了三种时间表示方式 通过text来存储时间文本 用整型来存储时间戳,时间戳是从1970-01-01算起的秒数 用浮点型来存储自儒略日开始算起的天数,儒略日即公元前4713年1月1日中午12点。 并且提供了一些

    2024年02月06日
    浏览(38)
  • Flutter/Dart日期格式化及时间戳转换

    点击进入我的自建博客链接 Dart 获取当前时间,以及获取当前年、月、日等。 创建指定时间还可以直接从符合日期格式的字符串直接转换,如下。 日期字符串转为时间 日期时间转成时间戳 时间戳转日期时间 可以给某个时间增加或减少时间段(Duration)。

    2024年02月11日
    浏览(38)
  • Java格式化日期,时间(三种方法,建议收藏)

    在java中String类格式化的方法,是静态format()用于创建格式化的字符串。 format(String format, Object... args) 新字符串使用本地语言环境,制定字符串格式和参数生成格式化的新字符串。 format(Locale locale, String format, Object... args) 使用指定的语言环境,制定字符串格式和参数生成格式化

    2024年02月15日
    浏览(34)
  • 使用 uni-app 开发项目,日期和时间如何格式化?

    功能需求描述 在开发项目时,往往需要对从后端查询到的时间进行格式化,查到的时间格式一般都是 时间戳 ,一堆数字,这时候怎么转化成类似于  2023年8月15日 08:12:10  这样的格式? 在组件显示格式化后的日期 其实 uni-app 的官方拓展组件  uni-dateformat  就能实现这个需求

    2024年02月05日
    浏览(36)
  • 【Java 基础篇】Java日期和时间格式化与解析指南:SimpleDateFormat详解

    日期和时间在软件开发中经常被用到,无论是用于记录事件、计算时间间隔还是格式化日期以供用户友好的展示。Java 提供了强大的日期和时间处理工具,其中 SimpleDateFormat 类是一个重要的工具,用于格式化日期和时间,同时也支持解析日期和时间。本篇博客将深入探讨 Sim

    2024年02月09日
    浏览(47)
  • 工作6年了日期时间格式化还在写YYYY疯狂给队友埋雷

    前言 哈喽小伙伴们好久不见,今天来个有意思的雷,看你有没有埋过。 正文 不多说废话,公司最近来了个外地回来的小伙伴,在广州工作过6年,也是一名挺有经验的开发。 他提交的代码被小组长发现有问题,给打回了,原因是里面日期格式化的用法有问题,用的SimpleDate

    2024年02月12日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包