发布时间:2026-07-21阅读(1)
日常开发中,Date对于我们来说是经常使用到的,平常使用的一些UI框架,如Antd、ElementUI等都会使用像moment.js、day.js的时间工具库去处理它们关于时间的组件,但当我们脱离这些框架,想去解决一个关于时间转换的问题,引入一个时间工具库就显得冗余了,由此这里给大家分享22个关于Date实用的一行Javascript与typescript代码大全,建议收藏阅读,今天小编就来聊一聊关于javascript日期获取?接下来我们就一起去研究一下吧!

javascript日期获取
日常开发中,Date对于我们来说是经常使用到的,平常使用的一些UI框架,如Antd、ElementUI等都会使用像moment.js、day.js的时间工具库去处理它们关于时间的组件,但当我们脱离这些框架,想去解决一个关于时间转换的问题,引入一个时间工具库就显得冗余了,由此这里给大家分享22个关于Date实用的一行Javascript与typescript代码大全,建议收藏阅读!
前置知识
Intl 对象是 ECMAScript 国际化 API 的一个命名空间,它提供了精确的字符串对比、数字格式化,和日期时间格式化。Collator,NumberFormat 和 DateTimeFormat 对象的构造函数是 Intl 对象的属性。了解更多
Intl.DateTimeFormat是根据语言来格式化日期和时间的对象的构造器
语法:
// locales为语言new Intl.DateTimeFormat([locales[, options]])Intl.DateTimeFormat.call(this[, locales[, options]])// 格式化对应语言得日期,date为Date实例,返回日期字符串new Intl.DateTimeFormat(locale).format(date)// 获取时区Intl.DateTimeFormat().resolvedOptions().timeZone22个关于Date实用的一行Javascript与typescript代码大全
为小时添加AM/PMJavaScript 版本
// `h` 是 0 到 23 之间的小时数const suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? am : pm}`;TypeScript 版本
const suffixAmPm = (h: number): string => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? am : pm}`;Demo
计算两个日期之间的差异天数
suffixAmPm(0); // 12amsuffixAmPm(5); // 5amsuffixAmPm(12); // 12pmsuffixAmPm(15); // 3pmsuffixAmPm(23); // 11pmJavaScript 版本
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));TypeScript 版本
const diffDays = (date: Date, otherDate: Date): number => Math.ceil(Math.abs(date.valueOf() - otherDate.valueOf()) / (1000 * 60 * 60 * 24));Demo
计算两个日期之间的月数
diffDays(new Date(2014-12-19), new Date(2020-01-01)); // 1839JavaScript 版本
const monthDiff = (startDate, endDate) => Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() endDate.getMonth());TypeScript 版本
const monthDiff = (startDate: Date, endDate: Date): number => Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() endDate.getMonth());Demo
比较两个日期
monthDiff(new Date(2020-01-01), new Date(2021-01-01)); // 12JavaScript 版本
// `a` 和 `b` 是 `Date` 实例const compare = (a, b) => a.getTime() > b.getTime();TypeScript 版本
const compare = (a: Date, b: Date): boolean => a.getTime() > b.getTime();Demo
将日期转换为 YYYY-MM-DD 格式
compare(new Date(2020-03-30), new Date(2020-01-01)); // trueJavaScript 版本
// `date` 是对象实例const formatYmd = (date) => date.toISOString().slice(0, 10);TypeScript 版本
const formatYmd = (date: Date): string => date.toISOString().slice(0, 10);Demo
将秒转换为 hh:mm:ss 格式
formatYmd(new Date()); // 2020-05-06JavaScript 版本
// `s` 秒数const formatSeconds = (s) => new Date(s * 1000).toISOString().substr(11, 8);// Orconst formatSeconds = (s) => new Date(s * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];// Orconst formatSeconds = (s) => [parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(:).replace(/\b(\d)\b/g, 0$1);TypeScript 版本
const formatSeconds = (s: number): string => new Date(s * 1000).toISOString().substr(11, 8);// Orconst formatSeconds = (s: number): string => (new Date(s * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/) as string[])[0];// Orconst formatSeconds = (s: number): string => ( [parseInt(`${s / 3600}`), parseInt(`${(s / 60) % 60}`), parseInt(`${s % 60}`)].join(:).replace(/\b(\d)\b/g, 0$1));Demo
从日期中提取年、月、日、时、分、秒和毫秒
formatSeconds(200); // 00:03:20formatSeconds(500); // 00:08:20JavaScript 版本
// `date` 是一个 `Date` 对象const extract = (date) => date .toISOString() .split(/[^0-9]/) .slice(0, -1);// `extract` 是一个 [年、月、日、小时、分钟、秒、毫秒] 的数组TypeScript 版本
const extract = (date: Date): string[] => date .toISOString() .split(/[^0-9]/) .slice(0, -1);Demo
格式化给定语言环境的日期
extract(new Date()); // [2021, 12, 09, 04, 48, 36, 600]JavaScript 版本
// `date` 是一个 `Date` 对象 // `locale` 是一个语言环境(例如 en-US、pt-BR)const format = (date, locale) => new Intl.DateTimeFormat(locale).format(date);TypeScript 版本
const format = (date: Date, locale: string): string => new Intl.DateTimeFormat(locale).format(date);Demo
获取日期的当前季度
format(new Date(), pt-BR); // 06/05/2020JavaScript 版本
const getQuarter = (d = new Date()) => Math.ceil((d.getMonth() 1) / 3);TypeScript 版本
以秒为单位获取当前时间戳
const getQuarter = (d = new Date()): number => Math.ceil((d.getMonth() 1) / 3);JavaScript 版本
const ts = () => Math.floor(new Date().getTime() / 1000);TypeScript 版本
从日期获取一年中的哪一天
const ts = (): number => Math.floor(new Date().getTime() / 1000);JavaScript 版本
// `date` 是一个 `Date` 对象 const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));TypeScript 版本
const dayOfYear = (date: Date): number => Math.floor((date.valueOf() - new Date(date.getFullYear(), 0, 0).valueOf()) / (1000 * 60 * 60 * 24));Demo
获取日期所在月份的第一个日期
dayOfYear(new Date(2020, 04, 16)); // 137JavaScript 版本
const getFirstDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth(), 1);TypeScript 版本
获取日期所在月份的最后一个日期
const getFirstDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth(), 1);JavaScript 版本
const getLastDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth() 1, 0);TypeScript 版本
获取日期的月份名称
const getLastDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth() 1, 0);JavaScript 版本
// `date` 是一个 Date 对象const getMonthName = (date) => [January, February, March, April, May, June, July, August, September, October, November, December][date.getMonth()];TypeScript 版本
获取给定月份的天数
const getMonthName = (date: Date): string => [January, February, March, April, May, June, July, August, September, October, November, December][date.getMonth()];JavaScript 版本
// `month` 是从零开始的索引const daysInMonth = (month, year) => new Date(year, month, 0).getDate();TypeScript 版本
获取时区字符串
const daysInMonth = (month: number, year: number): number => new Date(year, month, 0).getDate();JavaScript 版本
const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;TypeScript 版本
const getTimezone = (): string => Intl.DateTimeFormat().resolvedOptions().timeZone;Demo
获取明天的日期
getTimezone(); // Asia/SaigonJavaScript 版本
const tomorrow = ((d) => new Date(d.setDate(d.getDate() 1)))(new Date());// Orconst tomorrow = new Date(new Date().valueOf() 1000 * 60 * 60 * 24);TypeScript 版本
获取一年中的总天数
const tomorrow: Date = ((d) => new Date(d.setDate(d.getDate() 1)))(new Date());// Orconst tomorrow: Date = new Date(new Date().valueOf() 1000 * 60 * 60 * 24);JavaScript 版本
const numberOfDays = (year) => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365);// Orconst numberOfDays = (year) => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365);TypeScript 版本
获取日期的工作日
const numberOfDays = (year: number): number => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365);// Orconst numberOfDays = (year: number): number => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365);JavaScript 版本
// `date` is a Date objectconst getWeekday = (date) => [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday][date.getDay()];TypeScript 版本
获取昨天的日期
const getWeekday = (date: Date): string => [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday][date.getDay()];JavaScript 版本
const yesterday = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());// Orconst yesterday = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24);TypeScript 版本
初始化当前日期但将时间设置为午夜
const yesterday: Date = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());// Orconst yesterday: Date = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24);JavaScript 版本
const midnightOfToday = () => new Date(new Date().setHours(0, 0, 0, 0));TypeScript 版本
对日期数组进行排序
const midnightOfToday = (): Date => new Date(new Date().setHours(0, 0, 0, 0));JavaScript 版本
// `arr` 是一个包含 `Date` 项的数组const sortDescending = (arr) => arr.sort((a, b) => a.getTime() > b.getTime());const sortAscending = (arr) => arr.sort((a, b) => a.getTime() < b.getTime());TypeScript 版本
const sortDescending = (arr: Date[]): Date[] => arr.sort((a, b) => a.getTime() - b.getTime());const sortAscending = (arr: Date[]): Date[] => arr.sort((a, b) => b.getTime() - a.getTime());
上一篇:js时钟日期代码js日期工具类
下一篇:如何注册qq号 怎样注册qq号
Copyright © 2024 有趣生活 All Rights Reserve吉ICP备19000289号-5 TXT地图HTML地图XML地图