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

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

相关推荐
ifeng091819 小时前
HarmonyOS实战项目:打造智能家居控制中心(设备发现与控制)
wpf·智能家居·harmonyos
ifeng091821 小时前
HarmonyOS分布式数据管理——跨设备数据同步实战
harmonyos
ifeng09181 天前
HarmonyOS实战项目:开发一个分布式新闻阅读客户端
分布式·wpf·harmonyos
小范馆1 天前
通过 useEventBus 和 useEventCallBack 实现与原生 Android、鸿蒙、iOS 的事件交互
android·ios·harmonyos
爱笑的眼睛111 天前
HarmonyOS Text组件样式定制深度解析:从基础到高级实践
华为·harmonyos
ChinaDragon1 天前
HarmonyOS:弹出框层级管理
harmonyos
爱笑的眼睛111 天前
鸿蒙应用开发:华为静默登录解决方案
华为·harmonyos
用户498888174371 天前
ArkTS 语言基础 第九节:接口与抽象
harmonyos
纯爱掌门人1 天前
鸿蒙状态管理V2实战:从零构建MVVM架构的应用
前端·harmonyos
白鹿第一帅1 天前
【案例实战】鸿蒙元服务开发实战:从云原生到移动端,包大小压缩 96% 启动提速 75% 的轻量化设计
harmonyos·白鹿第一帅·鸿蒙元服务·csdn成都站·鸿蒙开放能力·鸿蒙学习之路·鸿蒙元服务框架