首页 > 其他分享 >TypeScript日期方法封装

TypeScript日期方法封装

时间:2024-03-26 21:59:24浏览次数:14  
标签:startDate TypeScript 封装 currentDate 日期 new Date return

TypeScript日期方法封装

1. 获取当前日期,格式YYYY-MM-DD
2. 获取当前时间,格式YYYY-MM-DD HH:mm:ss
3. 返回一年的总天数
4. 返回日期是当年第多少天
5. 返回时间范围的所有周末
6. 返回该日期的周末日期
7. 返回时间范围的各个月份的总天数
8. 返回日期范围内所有周末,一级前一个与后一个
9. 返回以四天为一段的日期数组
10. 返回时间范围的每一天日期对象
11. 返回日期所属的周末日期
12. 返回时间字符串
13. 返回星期字符串
/*
 * @Author: 杨文康  [email protected]
 * @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 "六";
    }
}

标签:startDate,TypeScript,封装,currentDate,日期,new,Date,return
From: https://blog.csdn.net/weixin_69868156/article/details/137058735

相关文章

  • Data.olllo解密:秒数转换为日期格式的神奇技能!
    引言:时间是数据世界中不可或缺的一环,而将秒数转换为易读的日期格式往往是数据处理中的一大挑战。但是,有了Data.olllo,这一任务将变得异常简单!功能介绍:Data.olllo的秒数转换功能可以让您轻松地将秒数格式的时间转换为标准的年月日时分秒的日期格式。这个功能不仅能够提高数据......
  • Element UI中日期选择日(date-picker)等其他选择器下拉显示错位、位置错误解决
    省流版给选择器加上唯一key(下面的想看就看)问题复现需求是用一个下拉切换时间维度的选择,分别为年度、季度、月度,但是开发的时候发现,当切换的时候,视图可正常切换,但点击选择时却发现选择器跑到了左上角,代码和问题截图如下:问题代码:<el-forminline><el-for......
  • 基于 Vue3 + Element-plus 封装的 Table 组件
    项目信息项目名称:vue3-xmw-table预览地址:点击预览Github:vue3-element-table使用方法根目录下执行npmivue3-xmw-table命令npmivue3-xmw-table全局挂载组件import{createApp}from'vue'importAppfrom'./App.vue'importXmwtablefrom'vue3-xmw-table'......
  • 还写那么多函数?js简单封装,拿去用吧
    ;(function($){ varwprtTheme={ //Maininitfunction init:function(){ this.config(); this.events(); }, //Definevarsforcaching config:function(){ ......
  • 前端学习-TypeScript-001-了解、安装TypeScript
    菜鸟教程链接TypeScript简介TypeScript是JavaScript的超集,扩展了JavaScript的语法,因此现有的JavaScript代码可与TypeScript一起工作无需任何修改,TypeScript通过类型注解提供编译时的静态类型检查。TypeScript可处理已有的JavaScript代码,并只对其中的TypeScript......
  • 面向对象08:封装详解
    packagecom.oop.demo04;//类private:私有publicclassStudent{//属性私有,封装大多数时候都是对于属性来的privateStringname;//名字,以前public所有人都可以操作这个名字,现在属性私有就不让所有人都可以操纵这个属性了privateintid;//学号priva......
  • TypeScript学习笔记之泛型
    介绍软件工程中,我们不仅要创建一致的定义良好的API,同时也要考虑可重用性。组件不仅能够支持当前的数据类型,同时也能支持未来的数据类型,这在创建大型系统时为你提供了十分灵活的功能。在像C#和Java这样的语言中,可以使用泛型来创建可重用的组件,一个组件可以支持多种类型的数据......
  • TypeScript划重点【纯干货版】
    7年前端因为不会吹牛逼在家待业中,有同学帮忙内推个职位吗?中级开发就行,不挑食(真tm卑微!!!)TypeScript的主要特点包括:基础类型数组Array【重点】元组Tuple枚举enum状态管理方向错误码配置选项联合类型(UnionTypes)交叉类型(IntersectionTypes)【重点】类型别名(TypeAliases)【重......
  • 【转载】基于Ado.Net多个关系型数据库DbHelper封装
    主要是记录一下,后续有用的时候再翻看。publicclassDbHelper{privatereadonlyDataBase_dataBase;publicDbHelper(DataBasedataBase){_dataBase=dataBase;}publicDataBaseGetDataBase(){......
  • aardio封装库) sunny抓包工具的使用
    前言还有个迭代器,基础语法基本已经说完了,后面想到啥再补充,之后的教程会从以下方面来讲:基础库的使用,比如string、table等基础控件的使用,比如listview、tab等aardio和Python交互,比如给Python写个界面自带的范例程序我写的一些小程序当然,我的理解也是很基础的,特别是在界面设......