文章目录背景一、HarmonyOS 日期处理的痛点二、核心方法getFormatDate三、时间戳自动补位四、核心方法getFormatDateStr五、今日信息快速获取六、完整 Demo 演示6.1 刷新当前时间6.2 格式化演示6.3 常用格式展示6.4 基础信息 UI6.5 intl.DateTimeFormat 格式化七、格式化结果示例八、API 速查表九、小结背景近期发现一款很有意思的HarmonyOS 三方库, 地址 pura/harmony-utils(V1.4.0) , 作者是桃花镇童长老, 我这里也是直接通过该作者公布的源码进行案例编写进行,写了到目前写了一部分demo ,感觉确实很有帮助,这里呢也是开始写一个系列的演示demo 供大家参考。如有帮助可以在OpenHarmony中进行下载安装进行使用哦案例demo导航展示↓↓↓↓↓↓接下来言归正传 ↓↓↓↓一、HarmonyOS 日期处理的痛点在 HarmonyOS 应用开发中日期处理涉及以下常见问题时间戳格式不一致后端接口有时返回 10 位秒、有时返回 13 位毫秒日期字符串格式多样2026-05-19、2026/05/19、2026年05月19日格式化模板不同场景需要不同的日期展示格式相对时间需要显示刚刚、3分钟前而非绝对时间DateUtil封装了 HarmonyOS 的intl.DateTimeFormat和原生DateAPI解决上述所有痛点。二、核心方法getFormatDate所有日期操作的基础将任意格式的输入统一转换为Date对象staticgetFormatDate(date?:number|string|Date):Date{if(dateundefined||datenull){//无参数datenewDate();}elseif(typeofdatestring){//字符串日期if(date.length0){datenewDate();}elseif(RegexUtil.isDigits(date)){//字符串类型的时间戳10-13位datenewDate(DateUtil.padTimestamp(date));}else{constdateStrDateUtil.formatDateStr(date);datenewDate(dateStr);}}elseif(typeofdatenumber){//时间戳10-13位datenewDate(DateUtil.padTimestamp(date));}returndate;}支持的输入格式无参数 → 返回当前时间number→ 10位/13位时间戳string数字 → 字符串时间戳string日期 → 多种格式自动识别-///中文Date→ 直接返回三、时间戳自动补位privatestaticpadTimestamp(dateNum:string|number):number{lettimestamp:number;if(typeofdateNumnumber){timestampdateNum;}else{timestampNumber(dateNum).valueOf();}if(timestamp.toString().length10){timestamptimestamp*1000;//如果是10位时间戳转为13位}elseif(timestamp.toString().length11){timestamptimestamp*100;//如果是11位时间戳转为13位}elseif(timestamp.toString().length12){timestamptimestamp*10;//如果是11位时间戳转为13位}returntimestamp;}自动将 10/11/12 位时间戳补齐为 13 位毫秒解决了后端接口时间戳格式不一致的问题。四、核心方法getFormatDateStrstaticgetFormatDateStr(date:number|string|Date,format?:string):string{dateDateUtil.getFormatDate(date)if(formatundefined||format.length0){formatDATE_FORMAT1;//yyyy-MM-dd HH:mm:ss}constyeardate.getFullYear();constmonthDateUtil.padZero(date.getMonth()1);constdayDateUtil.padZero(date.getDate());consthoursDateUtil.padZero(date.getHours());constminutesDateUtil.padZero(date.getMinutes());constsecondsDateUtil.padZero(date.getSeconds());constmilliseconddate.getMilliseconds();returnformat.replace(yyyy,year.toString()).replace(MM,month).replace(dd,day).replace(HH,hours).replace(mm,minutes).replace(ss,seconds).replace(fff,millisecond.toString());}格式化占位符占位符说明示例yyyy4位年份2026MM2位月份补零05dd2位日期补零19HH2位小时24小时15mm2位分钟30ss2位秒00fff毫秒1-3位123五、今日信息快速获取staticgetToday():Date// 获取今天的 Date 对象staticgetTodayTime():number// 获取今天的时间戳毫秒staticgetTodayStr(format?:string):string// 获取今天的格式化字符串staticgetNowYear():number// 当前年staticgetNowMonth():number// 当前月1-12staticgetNowDay():number// 当前日1-31六、完整 Demo 演示来自DateUtilDemoPage.ets6.1 刷新当前时间refreshNow(){this.nowDateDateUtil.getTodayStr(yyyy-MM-dd HH:mm:ss);this.nowTimestampDateUtil.getTodayTime().toString();this.nowYearDateUtil.getNowYear().toString();this.nowMonthDateUtil.getNowMonth().toString();this.nowDayDateUtil.getNowDay().toString();this.isLeapYearDateUtil.isLeapYear()?✅ 是闰年:❌ 平年;this.addLog(Date,当前时间:${this.nowDate},info);}6.2 格式化演示doFormat(){try{constresultDateUtil.getFormatDateStr(this.formatInput,this.formatPattern);this.formatResultresult;this.addLog(Format,${this.formatInput} → ${result},success);}catch(e){this.formatResult错误:${(easError).message};this.addLog(Format,格式化失败:${(easError).message},error);}}6.3 常用格式展示getFormatExamples():FormatExample[]{constnownewDate();return[{pattern:yyyy-MM-dd,result:DateUtil.getFormatDateStr(now,yyyy-MM-dd),desc:标准日期},{pattern:yyyy-MM-dd HH:mm:ss,result:DateUtil.getFormatDateStr(now,yyyy-MM-dd HH:mm:ss),desc:完整时间},{pattern:HH:mm:ss,result:DateUtil.getFormatDateStr(now,HH:mm:ss),desc:仅时间},{pattern:yyyy年MM月dd日,result:DateUtil.getFormatDateStr(now,yyyy年MM月dd日),desc:中文格式},{pattern:yyyy/MM/dd,result:DateUtil.getFormatDateStr(now,yyyy/MM/dd),desc:斜杠分隔},{pattern:yyyy-MM-dd fff,result:DateUtil.getFormatDateStr(now,yyyy-MM-dd fff),desc:含毫秒},];}6.4 基础信息 UI// 年月日展示Row(){Column(){Text(this.nowYear).fontSize(20).fontWeight(FontWeight.Bold).fontColor(#4080FF)Text(年).fontSize(11).fontColor(#888)}.layoutWeight(1).alignItems(HorizontalAlign.Center)Column(){Text(this.nowMonth).fontSize(20).fontWeight(FontWeight.Bold).fontColor(#4080FF)Text(月).fontSize(11).fontColor(#888)}.layoutWeight(1).alignItems(HorizontalAlign.Center)Column(){Text(this.nowDay).fontSize(20).fontWeight(FontWeight.Bold).fontColor(#4080FF)Text(日).fontSize(11).fontColor(#888)}.layoutWeight(1).alignItems(HorizontalAlign.Center)Column(){Text(DateUtil.getWeekDay(newDate()).toString()).fontSize(20).fontWeight(FontWeight.Bold).fontColor(DateUtil.isWeekend(newDate())?#FF5252:#00C853)Text(周${[日,一,二,三,四,五,六][DateUtil.getWeekDay(newDate())]}).fontSize(11).fontColor(#888)}.layoutWeight(1).alignItems(HorizontalAlign.Center)Column(){Text(DateUtil.getWeekOfMonth(newDate()).toString()).fontSize(20).fontWeight(FontWeight.Bold).fontColor(#FF9800)Text(当月第几周).fontSize(11).fontColor(#888)}.layoutWeight(1).alignItems(HorizontalAlign.Center)}6.5 intl.DateTimeFormat 格式化// getFormatTime 使用 intl.DateTimeFormatRow(){Text(getFormatTime:).fontSize(11).fontFamily(monospace).fontColor(#D63384)Text(DateUtil.getFormatTime(newDate(),{dateStyle:full,timeStyle:medium})).fontSize(11).fontColor(#555).margin({left:4})}.width(100%).padding({top:4,bottom:4})// 相对时间Row(){Text(getFormatRelativeTime:).fontSize(11).fontFamily(monospace).fontColor(#D63384)Text(DateUtil.getFormatRelativeTime(-3,day)).fontSize(11).fontColor(#555).margin({left:4})}.width(100%).padding({top:4,bottom:4})getFormatRelativeTime(-3, day)会输出类似3天前的本地化相对时间字符串。七、格式化结果示例以2026-05-19 15:30:45.123为例格式模板输出结果yyyy-MM-dd2026-05-19yyyy-MM-dd HH:mm:ss2026-05-19 15:30:45HH:mm:ss15:30:45yyyy年MM月dd日2026年05月19日yyyy/MM/dd2026/05/19yyyy-MM-dd fff2026-05-19 123MM月dd日05月19日八、API 速查表方法说明getFormatDate(date?)将任意格式转为 Date 对象getFormatDateStr(date, format?)格式化为指定格式的字符串getToday()获取当天 Date 对象getTodayTime()获取当天时间戳msgetTodayStr(format?)获取当天格式化字符串getNowYear/Month/Day()获取当前年/月/日isLeapYear(year?)判断是否为闰年getFormatTime(date, options?, locale?)使用 intl.DateTimeFormat 格式化getFormatRelativeTime(value, unit, ...)格式化相对时间如3天前九、小结DateUtil的日期格式化功能是其核心部分getFormatDate是基础处理了所有常见的输入格式含10/13位时间戳自动补位getFormatDateStr支持自由组合的格式模板yyyy-MM-dd HH:mm:ss fff应有尽有getFormatTime利用intl.DateTimeFormat实现本地化的日期格式getFormatRelativeTime实现3天前这类人性化的相对时间掌握这几个方法日期格式化问题迎刃而解。