TypeScript日期方法封装

TypeScript日期方法封装

1. 获取当前日期,格式YYYY-MM-DD
2. 获取当前时间,格式YYYY-MM-DD HH:mm:ss
3. 返回一年的总天数
4. 返回日期是当年第多少天
5. 返回时间范围的所有周末
6. 返回该日期的周末日期
7. 返回时间范围的各个月份的总天数
8. 返回日期范围内所有周末,一级前一个与后一个
9. 返回以四天为一段的日期数组
10. 返回时间范围的每一天日期对象
11. 返回日期所属的周末日期
12. 返回时间字符串
13. 返回星期字符串
/*
 * @Author: 杨文康  ywk719@163.com
 * @Date: 2023-12-10 23:57:21
 * @Description: Date 转字符串
 */

//获取当前日期,格式YYYY-MM-DD
export function getNowFormatDay(nowDate: Date | null = null, char: string = "-") {
    if (nowDate == null) {
        nowDate = new Date();
    }
    let day = nowDate.getDate();
    let month = nowDate.getMonth() + 1;//注意月份需要+1
    let year = nowDate.getFullYear();
    //补全0,并拼接
    return year + char + completeDate(month) + char + completeDate(day);
}

//获取当前时间,格式YYYY-MM-DD HH:mm:ss
export function getNowFormatTime(nowDate: Date | null = null, char: string = "-", colon: string = ":", bool: boolean = false) {
    // let nowDate = new Date();
    // let colon = ":";
    if (nowDate == null) {
        nowDate = new Date();
    }
    let h = nowDate.getHours();
    let m = nowDate.getMinutes();
    let s = nowDate.getSeconds();
    //补全0,并拼接
    if (bool) {
        return [getNowFormatDay(nowDate, char), completeDate(h) + colon + completeDate(m) + colon + completeDate(s)];
    }
    return getNowFormatDay(nowDate, char) + " " + completeDate(h) + colon + completeDate(m) + colon + completeDate(s);
}

//补全0
function completeDate(value: number) {
    return value < 10 ? "0" + value : value;
}

/**
 * 
 * @param year 年份
 * @returns 返回一年的总天数
 */
export const allDays = (year: number) => {
    let leapYear = false, sum_day = 0, month_arr = [4, 6, 9, 11];
    if (year % 100 === 0) { // 年份是整百
        leapYear = year % 400 === 0
    } else {
        leapYear = year % 4 === 0
    }
    // 下面计算每个月的天数
    for (let i = 1; i < 13; i++) {
        if (i === 2) {
            sum_day += leapYear ? 29 : 28
        } else if (month_arr.includes(i)) {
            sum_day += 30
        } else {
            sum_day += 31
        }
    }
    return sum_day
}

/**
 * 
 * @param s 日期 YYYY-MM-DD风格
 * @returns 返回日期是当年第多少天
 */
export function getDays(s: `${number}-${number}-${number}`) {
    const arr: any = s.split('-')
    const d1 = new Date(arr[0], 0, 0).getTime()
    const d2 = new Date(arr[0], arr[1] - 1, arr[2]).getTime()
    const d = Math.floor((d2 - d1) / (1000 * 60 * 60 * 24))
    return d
}




/**
 * 
 * @param startDate 开始时间
 * @param endDate 结束时间
 * @returns 返回时间范围的所有周末
 */
export function getSundayDates(startDate: Date, endDate: Date) {
    /* startDate = new Date(startDate)
    endDate = new Date(endDate) */
    const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
    const result: Date[] = [];

    let currentSunday = getNextSunday(startDate); // 获取起始日期所在周的周日日期

    while (currentSunday <= endDate) {
        result.push(currentSunday);
        currentSunday = new Date(currentSunday.getTime() + 7 * oneDay); // 下一周的周日日期
    }
    let weekend = getWeekends(startDate, endDate)
    // console.log(weekend[0].previousWeekend);
    result.unshift(weekend[0].previousWeekend)

    return result;
}

/**
 * 
 * @param date 日期对象
 * @returns 返回该日期的周末日期
 */
function getNextSunday(date: Date) {
    const dayOfWeek = date.getDay(); // 获取当前日期的星期几(0 表示周日,1 表示周一,以此类推)
    const daysUntilNextSunday = 7 - dayOfWeek; // 距离下一个周日的天数
    const nextSunday = new Date(date.getTime() + daysUntilNextSunday * 24 * 60 * 60 * 1000); // 下一个周日的日期
    return nextSunday;
}


/**
 * 
 * @param startDate 开始日期
 * @param endDate 结束日期
 * @returns 返回时间范围的各个月份的总天数
 */
export function getMonthDays(startDate: Date, endDate: Date) {
    const months: {
        year: number,
        month: number,
        days: number
    }[] = [];
    // let currentDate = new Date(startDate);

    while (startDate <= endDate) {
        const year = startDate.getFullYear();
        const month = startDate.getMonth();
        const daysInMonth = new Date(year, month + 1, 0).getDate();

        months.push({
            year: year,
            month: month + 1,
            days: daysInMonth
        });

        startDate.setMonth(month + 1);
    }

    return months;
}

interface IgetWeekends {
    /**当前日期 */
    date: Date,
    /**上一个日期 */
    previousWeekend: Date,
    /**下一个日期 */
    nextWeekend: Date
}
/**
 * 
 * @param startDate 
 * @param endDate 
 * @returns 返回日期范围内所有周末,一级前一个与后一个
 */
function getWeekends(startDate: any, endDate: any): Array<IgetWeekends> {
    const weekends: IgetWeekends[] = [];
    let currentDate = new Date(startDate);

    while (currentDate <= endDate) {
        const dayOfWeek = currentDate.getDay();

        if (dayOfWeek === 0) {
            weekends.push({
                date: new Date(currentDate),
                previousWeekend: getPreviousWeekend(currentDate),
                nextWeekend: getNextWeekend(currentDate)
            });
        }

        currentDate.setDate(currentDate.getDate() + 1);
    }

    return weekends;
}

/**前一个 */
function getPreviousWeekend(date: Date) {
    const previousDate = new Date(date);
    previousDate.setDate(previousDate.getDate() - 1);

    while (previousDate.getDay() !== 0) {
        previousDate.setDate(previousDate.getDate() - 1);
    }

    return new Date(previousDate);
}

/** 后一个 */
function getNextWeekend(date: any) {
    const nextDate = new Date(date);
    nextDate.setDate(nextDate.getDate() + 1);

    while (nextDate.getDay() !== 0) {
        nextDate.setDate(nextDate.getDate() + 1);
    }

    return new Date(nextDate);
}

/**
 * 
 * @param startDate 开始日期
 * @param endDate 结束日期
 * @returns 返回以四天为一段的日期数组
 */
export function getDates(startDate: Date, endDate: Date) {
    const dates: Date[] = [];
    let currentDate = new Date(startDate);

    while (currentDate <= endDate) {
        dates.push(new Date(currentDate));
        currentDate.setDate(currentDate.getDate() + 4);
    }

    return dates;
}

/**
 * 
 * @param startDate 开始时间
 * @param endDate 结束时间
 * @returns 返回时间范围的每一天日期对象
 */
export function getDate(startDate: Date, endDate: Date) {
    const dates: Date[] = [];
    let currentDate = new Date(startDate);

    while (currentDate <= endDate) {
        dates.push(new Date(currentDate));
        currentDate.setDate(currentDate.getDate() + 1);
    }

    return dates;
}


/**
 * 
 * @param currentDate 日期对象
 * @return {TYPE} 返回日期所属的周末日期
 */
export function recentlyWeek(currentDate: Date): Date {
    // let currentDate = new Date(endTime);
    while (currentDate.getDay() < 6) {
        currentDate = new Date(currentDate);
        currentDate.setDate(currentDate.getDate() + 1);
    }
    return currentDate;
}

/**
 * 日期转字符串
 * @param date 日期
 * @param fame 拼接符 /
 * @returns 返回时间字符串
 */
export let DateTime = (date: Date, fame = "/") => {
    return date.getFullYear() + fame + (date.getMonth() + 1) + fame + date.getDate()
}

/**
 * 
 * @param date 日期
 * @return {string} 星期字符串
 */
export let textWeek=(date: Date=new Date())=>{
    switch (date.getDay()) {
        case 0:
            return "日";
        case 1:
            return "一";
        case 2:
            return "二";
        case 3:
            return "三";
        case 4:
            return "四";
        case 5:
            return "五";
        default:
            return "六";
    }
}

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CrazyBrainYWK

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值