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

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

相关推荐
光锥智能32 分钟前
华为MateBook 14 鸿蒙版发布,体验全面升维
华为·harmonyos
UnicornDev43 分钟前
【HarmonyOS 6】练习记录页面 UI 设计
ui·华为·harmonyos·arkts·鸿蒙
浮芷.1 小时前
生命科学数据视界防御:基于鸿蒙Flutter陀螺仪云台与三维体积光栅的视轴锁定架构
flutter·华为·架构·开源·harmonyos·鸿蒙
浮芷.1 小时前
微观搜打撤:基于鸿蒙flutter的内存快照算法的局内外状态隔离与高阶背包系统设计
算法·flutter·华为·开源·harmonyos·鸿蒙
浮芷.1 小时前
东方修仙模拟器:基于 鸿蒙Flutter 状态机与 CustomPainter 的境界跃升与天劫渲染架构
科技·flutter·华为·架构·开源·harmonyos·鸿蒙
民乐团扒谱机2 小时前
基于ArkTS与端云协同的鸿蒙智慧校园助手——项目报告(AIGC预警⚠️)
华为·aigc·harmonyos
互联网散修2 小时前
鸿蒙实战:运动健康类应用核心组件——语音播报模块设计与实现
华为·harmonyos·tts·语音播报
想你依然心痛2 小时前
HarmonyOS 6智能家居实战:基于悬浮导航与沉浸光感的“光影智家“全屋智能控制系统
华为·智能家居·harmonyos·智能控制·悬浮导航·沉浸光感
雪芽蓝域zzs2 小时前
uni-app x 中使用 UTS 语言实现兼容鸿蒙的加密
华为·uni-app·harmonyos
条tiao条2 小时前
鸿蒙 ArkTS 学习入门
学习·华为·harmonyos