JS实用的一行代码(Date系列)

从十进制时间获取小时和分钟
const getHoursAndMinutes = (value) => [Math.floor(value), Math.floor((value * 60) % 60)];

getHoursAndMinutes(4.5); 
//[4, 30]
getHoursAndMinutes(7.89); 
// [7, 53]
一年后现在的时间
const plusOneYear = ((d) => new Date(d.setFullYear(d.getFullYear() + 1)))(new Date());
获取一年中的总天数
const numberOfDays = (year) => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365);
// Or
const numberOfDays = (year) => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365);
计算两个日期之间的月数
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 yesterday = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());
// Or
const yesterday = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24);
获取明天的日期
const tomorrow = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date());
// Or
const tomorrow = new Date(new Date().valueOf() + 1000 * 60 * 60 * 24);
将秒转换为 hh:mm:ss 格式
const formatSeconds = (s) => new Date(s * 1000).toISOString().substr(11, 8);
// Or
const formatSeconds = (s) => new Date(s * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
// Or
const formatSeconds = (s) =>
    [parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(':').replace(/\b(\d)\b/g, '0$1');

formatSeconds(200); 
// 00:03:20
formatSeconds(500); 
// 00:08:20
获取当前月份的名称
// date 是一个日期对象
const getMonthName = (date) =>
    [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        ' November',
        'December',
    ][date.getMonth()];
将日期转换为 YYYY-MM-DD 格式
// date 是一个Date对象
const formatYmd = (date) => date.toISOString().slice(0, 10);

formatYmd(new Date()); 
// 2020-05-06

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值