时间戳转时间 - 鸿蒙 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
  }
}

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

相关推荐
Simon席玉1 小时前
C++的命名重整
开发语言·c++·华为·harmonyos·arkts
我是Feri2 小时前
HarmonyOS 6.0 视频播放组件使用教程
华为·音视频·harmonyos
大土豆的bug记录4 小时前
鸿蒙权限授权弹窗(推荐)
华为·harmonyos
马剑威(威哥爱编程)4 小时前
【鸿蒙开发案例篇】基于MindSpore Lite的端侧人物图像分割案例
华为·harmonyos
L、2185 小时前
Flutter + OpenHarmony + 区块链:构建去中心化身份认证系统(DID 实战)
flutter·华为·去中心化·区块链·harmonyos
遇到困难睡大觉哈哈6 小时前
Harmony os —— Data Augmentation Kit 知识问答实战全流程(流式 RAG 问答踩坑记录)
harmonyos·鸿蒙
L、2187 小时前
Flutter + OpenHarmony 全栈实战:打造“鸿蒙智联”智能家居控制中心(系列终章)
flutter·华为·智能手机·electron·智能家居·harmonyos
马剑威(威哥爱编程)8 小时前
【鸿蒙开发案例篇】火力全开:鸿蒙6.0游戏开发战术手册
华为·harmonyos
L、2189 小时前
Flutter + OpenHarmony 分布式能力融合:实现跨设备 UI 共享与协同控制(终极篇)
javascript·分布式·flutter·ui·智能手机·harmonyos
鸿蒙开发工程师—阿辉9 小时前
HarmonyOS 5 极致动效实验室: Canvas 高阶动画的实现
华为·harmonyos