Date Time相关处理

给时间添加 am或pm

// 'h' is an hour number

const suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;
suffixAmPm(0); // '12am'
suffixAmPm(5); // '5am'
suffixAmPm(12); // '12pm'
suffixAmPm(15); // '3pm'
suffixAmPm(23); // '11pm'
计算两个日期之间的月份间隔
const monthDiff = (startDate, endDate) => Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
monthDiff(new Date('2020-01-01'), new Date('2021-01-01')); // 12
计算两个日期之间的日子间隔
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839
比较两个日期谁大谁小
const compare = (a: Date, b: Date): boolean => a.getTime() > a.getTime();
compare(new Date('2020-03-30'), new Date('2020-01-01')); // true
日期格式化(YYYY-MM-DD)
const formatYmd = (date) => date.toISOString().slice(0, 10);
formatYmd(new Date()); // 2020-05-06
秒格式化(hh:mm:ss)
// `s` is number of seconds
const formatSeconds = (s) => new Date(s * 1000).toISOString().substr(11, 8);
formatSeconds(200); // 00:03:20
formatSeconds(500); // 00:08:20
将数组进行解压
const unzip = (arr) =>
arr.reduce(
(acc, c) => (c.forEach((v, i) => acc[i].push(v)), acc),
Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_) => [])
);
unzip([
['a', 1],
['b', 2],
['c', 3],
['d', 4],
['e', 5],
]); // [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]]
根据某个日期得到该年剩下多少天
// `date` is a Date object
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));
dayOfYear(new Date(2020, 04, 16)); // 137
根据日期得到当前在第几个季度(quarter)
const getQuarter = (d = new Date()) => Math.ceil((d.getMonth() + 1) / 3);
获得当前秒格式下的时间戳
const ts = () => Math.floor(new Date().getTime() / 1000);
根据数据得到数字格式下的小时和分钟
const getHoursAndMinutes = (value) => [Math.floor(value), Math.floor((value * 60) % 60)];
getHoursAndMinutes(4.5); //[4, 30]
getHoursAndMinutes(7.89); // [7, 53]
以本地格式格式化日期
// `date` is a `Date` object
// `locale` is a locale (en-US, pt-BR, for example)
const format = (date, locale) => new Intl.DateTimeFormat(locale).format(date);
format(new Date(), 'pt-BR'); // 06/05/2020
根据日期得到当前英文的月份名称
// `date` is a Date object
const getMonthName = (date) => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', ' November', 'December'][date.getMonth()];
初始化一个当前处在凌点的日期
const midnightOfToday = () => new Date(new Date().setHours(0, 0, 0, 0));
检查当前是否在浏览器中
const isBrowser = typeof window === 'object' && typeof document === 'object';
``
posted @   Felix_Openmind  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}
点击右上角即可分享
微信分享提示