时间戳转时间 - 鸿蒙 HarmonyOS Next

开发中常见的时间与时间戳间相互转换的需要,如下是基于系统 api 的 import systemDateTime from '@ohos.systemDateTime'; 实现;

具体实现如下:

复制代码
import systemDateTime from '@ohos.systemDateTime'

/*公共方法类*/
export class PublicUtils {
  /**
   * 时间戳转时间
   * PublicUtils.getDateTime(systemDateTime.getTime(), 'yyyy-MM-dd HH:mm:ss')
   * @param time 时间戳(默认获取当前时间)
   * @param type 时间格式(默认'yyyy-MM-dd HH:mm')
   * @returns
   */
  static getDateTime(time: number | null, type: string | null): string {
    let date = new Date(systemDateTime.getTime())
    if (time) {
      date = new Date(time)
    }
    // 获取时间
    const year = date.getFullYear().toString()
    let month = (date.getMonth() + 1).toString()
    let day = date.getDate().toString()
    let hour = date.getHours().toString()
    let min = date.getMinutes().toString()
    let seconds = date.getSeconds().toString()
    // 补位
    month = month.length === 1 ? `0${month}` : month
    day = day.length === 1 ? `0${day}` : day
    hour = hour.length === 1 ? `0${hour}` : hour
    min = min.length === 1 ? `0${min}` : min
    seconds = seconds.length === 1 ? `0${seconds}` : seconds
    // 默认格式:年月日
    type = type ? type : 'yyyy-MM-dd'
    // 格式转换
    let timeStr = `${year}-${month}-${day}` // 默认 yyyy-mm-dd
    if (type === 'yyyy-MM-dd HH:mm:ss') {
      timeStr = `${year}-${month}-${day} ${hour}:${min}:${seconds}`
    } else if (type === 'yyyy-MM-dd HH:mm') {
      timeStr = `${year}-${month}-${day} ${hour}:${min}`
    } else if (type === 'yyyy-MM-dd') {
      timeStr = `${year}-${month}-${day}`
    } else if (type === 'yyyy-MM') {
      timeStr = `${year}-${month}`
    } else if (type === 'HH:mm:ss') {
      timeStr = `${hour}:${min}:${seconds}`
    } else if (type === 'HH:mm') {
      timeStr = `${hour}:${min}`
    }
    // callback
    return timeStr
  }
}

以上便是此次分享的全部内容,希望能对大家有所帮助!

相关推荐
王二蛋与他的张大花3 小时前
HarmonyOS运动开发:如何用mpchart绘制运动配速图表
harmonyos
程序员小刘3 小时前
【HarmonyOS 5】生活与服务开发实践详解以及服务卡片案例
华为·生活·harmonyos
小草帽学编程7 小时前
鸿蒙Next开发真机调试签名申请流程
android·华为·harmonyos
陈奕昆7 小时前
5.2 HarmonyOS NEXT应用性能诊断与优化:工具链、启动速度与功耗管理实战
华为·harmonyos
哼唧唧_11 小时前
React Native开发鸿蒙运动健康类应用的项目实践记录
react native·harmonyos·harmony os5·运动健康
二流小码农18 小时前
鸿蒙开发:实现一个标题栏吸顶
android·ios·harmonyos
坚果的博客19 小时前
uniappx插件nutpi-idcard 开发与使用指南(适配鸿蒙)
华为·harmonyos
程序员小刘19 小时前
【HarmonyOS 5】 社交行业详解以及 开发案例
华为·harmonyos
软件测试小仙女19 小时前
鸿蒙APP测试实战:从HDC命令到专项测试
大数据·软件测试·数据库·人工智能·测试工具·华为·harmonyos
Raink老师19 小时前
鸿蒙任务项设置案例实战
harmonyos·鸿蒙·案例实战