在日常开发中,我们经常会用到Date,一些常用的UI框架,比如Antd、ElementUI等,都会用到moments.js,day.js的时间工具库是用来处理他们与时间相关的组件的,但是当我们脱离这些框架,想要解决一个时间转换的问题时,引入一个时间工具库是多余的,所以分享一下与你共22篇关于Date的实用单行Javascript和typescript代码合集,推荐收藏阅读!前置知识Intl对象是ECMAScript国际化API的命名空间,提供精确的字符串比较、数字格式化、日期时间格式化。Collat??or、NumberFormat和DateTimeFormat对象的构造函数是Intl对象的属性。了解更多Intl.DateTimeFormat是根据语言格式化日期和时间对象的构造函数语法://localesislanguagenewIntl.DateTimeFormat([locales[,options]])Intl.DateTimeFormat.call(this[,locales[,options]])//格式化相应语言的日期,date是一个Date实例,返回日期字符串newIntl.DateTimeFormat(locale).format(date)//获取时区Intl.DateTimeFormat().resolvedOptions().timeZone22有用的Javascript和typescript代码行DateaddAM/PMJavaScriptversionforhour//`h`是0到23之间的小时数constsuffixAmPm=(h)=>`${h%12===0?12:h%12}${h<12?'am':'pm'}`;TypeScriptversionconstsuffixAmPm=(h:number):string=>`${h%12===0?12:h%12}${h<12?'am':'pm'}`;DemosuffixAmPm(0);//'12am'后缀AmPm(5);//'5am'后缀AmPm(12);//'12pm'后缀AmPm(15);//'3pm'后缀AmPm(23);//'11pm'计算两个日期之间的天数差JavaScriptversionconstdiffDays=(date,otherDate)=>Math.ceil(Math.abs(date-otherDate)/(1000*60*60*24));TypeScript版本constdiffDays=(date:Date,otherDate:Date):number=>Math.ceil(Math.abs(date.valueOf()-otherDate.valueOf())/(1000*60*60*24));DemodiffDays(新日期('2014-12-19'),新日期('2020-01-01'));//1839计算两个日期之间的月份JavaScript版本constmonthDiff=(startDate,endDate)=>Math.max(0,(endDate.getFullYear()-startDate.getFullYear())*12-startDate.getMonth()+endDate.getMonth());TypeScript版本constmonthDiff=(startDate:Date,endDate:Date):number=>Math.max(0,(endDate.getFullYear()-startDate.getFullYear())*12-startDate.getMonth()+endDate.getMonth());DemomonthDiff(新日期('2020-01-01'),新日期('2021-01-01'));//12比较两个日期JavaScript版本//`a`和`b`是`Date`示例constcompare=(a,b)=>a.getTime()>b.getTime();TypeScript版本constcompare=(a:Date,b:Date):boolean=>a.getTime()>b.getTime();Democompare(newDate('2020-03-30'),newDate('2020-01-01'));//true将日期转换为YYYY-MM-DD格式JavaScript版本//`date`是一个对象实例constformatYmd=(date)=>date.toISOString().slice(0,10);TypeScript版本constformatYmd=(date:Date):string=>date.toISOString().slice(0,10);DemoformatYmd(newDate());//2020-05-06将秒数转换为hh:mm:ss格式JavaScript版本//`s`秒数constformatSeconds=(s)=>newDate(s*1000).toISOString().substr(11,8);//OrconstformatSeconds=(s)=>newDate(s*1000).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];//OrconstformatSeconds=(s)=>[parseInt(s/60/60),parseInt((s/60)%60),parseInt(s%60)].join(':').replace(/\b(\d)\b/g,'0$1');TypeScriptversionconstformatSeconds=(s:number):string=>newDate(s*1000).toISOString().substr(11,8);//OrconstformatSeconds=(s:number):string=>(newDate(s*1000).toUTCString().match(/(\d\d:\d\d:\d\d)/)作为字符串[])[0];//OrconstformatSeconds=(s:number):string=>([parseInt(`${s/3600}`),parseInt(`${(s/60)%60}`),parseInt(`${s%60}`)].join(':').replace(/\b(\d)\b/g,'0$1'));DemoformatSeconds(200);//00:03:20格式秒数(500);//00:08:20提取年、月、日、小时、分钟、秒和毫秒JavaScript版本//`date`是一个`Date`objectconstextract=(date)=>date.toISOString().split(/[^0-9]/).slice(0,-1);//`extract`是一个[year,month,日、时、分、秒、毫秒数组]TypeScriptversionconstextract=(date:Date):string[]=>date.toISOString().split(/[^0-9]/).slice(0,-1);演示提取(新日期());//['2021','12','09','04','48','36','600']格式化给定的语言环境日期JavaScript版本//`date`是一个`Date`对象//`locale`是语言环境(例如en-US、pt-BR)constformat=(date,locale)=>newIntl.DateTimeFormat(locale).format(date);TypeScriptversionconstformat=(date:Date,locale:string):string=>newIntl.DateTimeFormat(locale).format(date);Demoformat(newDate(),'pt-BR');//06/05/2020获取日期JavaScript版本的当前季度constgetQuarter=(d=newDate())=>Math.ceil((d.getMonth()+1)/3);TypeScript版本constgetQuarter=(d=newDate()):number=>Math.ceil((d.getMonth()+1)/3);以秒为单位获取当前时间戳JavaScriptversionconstts=()=>Math.floor(newDate().getTime()/1000);TypeScript版本constts=():number=>Math.floor(newDate().getTime()/1000);从日期获取年份JavaScript版本//`date`是一个`Date`对象constdayOfYear=(date)=>Math.floor((date-newDate(date.getFullYear(),0,0))/(1000*60*60*24));TypeScript版本constdayOfYear=(date:Date):number=>Math.floor((date.valueOf()-newDate(date.getFullYear(),0,0).valueOf())/(1000*60*60*24));DemodayOfYear(新日期(2020,04,16));//137获取日期所在月份的第一个日期JavaScriptversionconstgetFirstDate=(d=newDate())=>newDate(d.getFullYear(),d.getMonth(),1);TypeScript版本constgetFirstDate=(d=newDate()):Date=>newDate(d.getFullYear(),d.getMonth(),1);获取日期为JavaScriptVersion的月份的最后一个日期constgetLastDate=(d=newDate())=>newDate(d.getFullYear(),d.getMonth()+1,0);TypeScript版本constgetLastDate=(d=newDate()):Date=>newDate(d.getFullYear(),d.getMonth()+1,0);获取日期JavaScript版本的月份名称//`date`是一个Date对象constgetMonthName=(日期)=>['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'][date.getMonth()];TypeScript版本constgetMonthName=(date:Date):string=>['January','February','March','April','May','June','July','August','September','十月','十一月','十二月'][date.getMonth()];获取给定月份的天数JavaScript版本//`month`是从零开始的IndexofconstdaysInMonth=(month,year)=>newDate(year,month,0).getDate();TypeScript版本constdaysInMonth=(month:number,year:number):number=>newDate(year,month,0).getDate();获取时区字符串JavaScript版本constgetTimezone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone;TypeScript版本constgetTimezone=():string=>Intl.DateTimeFormat()。resolvedOptions().timeZone;DemogetTimezone();//'Asia/Saigon'获取明天的日期JavaScript版本consttomorrow=((d)=>newDate(d.setDate(d.getDate()+1)))(newDate());//Orconsttomorrow=新日期(新日期().valueOf()+1000*60*60*24);明天的TypeScript版本常量:Date=((d)=>newDate(d.setDate(d.getDate()+1)))(newDate());//Orconsttomorrow:Date=newDate(newDate().valueOf()+1000*60*60*24);获取一年中的总天数JavaScriptversionconstnumberOfDays=(year)=>((year%4===0&&year%100!==0)||year%400===0?366:365);//OrconstnumberOfDays=(year)=>(newDate(year,1,29).getDate()===29?366:365);TypeScriptversionconstnumberOfDays=(year:number):number=>((year%4===0&&year%100!==0)||year%400===0?366:365);//OrconstnumberOfDays=(year:number):number=>(newDate(year,1,29).getDate()===29?366:365);WeekdayJavaScriptversion//`date`是一个Date对象constgetWeekday=(date)=>['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][日期.getDay()];TypeScript版本constgetWeekday=(date:Date):string=>['Sunday','Monday','Tuesday','Wednesday','星期四','星期五','星期六'][date.getDay()];获取昨天的日期JavaScriptversionconstyesterday=((d)=>newDate(d.setDate(d.getDate()-1)))(newDate());//Orconstyesterday=newDate(newDate().valueOf()-1000*60*60*24);TypeScriptversionconstyesterday:Date=((d)=>newDate(d.setDate(d.getDate()-1)))(newDate());//Orconstyesterday:Date=newDate(newDate().valueOf()-1000*60*60*24);初始化当前日期但将时间设置为午夜JavaScript版本constmidnightOfToday=()=>newDate(newDate().setHours(0,0,0,0));TypeScript版本constmidnightOfToday=():Date=>newDate(newDate().setHours(0,0,0,0));排序日期数组JavaScript版本//`arr`是一个包含`Date`项的数组constsortDescending=(arr)=>arr.sort((a,b)=>a.getTime()>b.getTime());constsortAscending=(arr)=>arr.sort((a,b)=>a.getTime()
