时间管理大师之时间戳(鸿蒙版)

461 阅读1分钟

前言

  • 时间戳是一个表示特定时间的数字,通常以秒或毫秒为单位。它表示自某个特定时刻(通常是1970年1月1日00:00:00 UTC,即 Unix 纪元)以来经过的时间。时间戳广泛用于计算机系统和编程中,以便进行日期和时间的存储、比较和处理。

获得时间戳

const  nowTime:number=new Date().getTime()
console.log('',nowTime)

@Entry
@Component
struct Index {
  build() {
    Column(){
    }
    }
}

image.png

如上图所示 1730276475119 便是在当时获取到的时间戳

直接获得年月日信息

const date:Date=new Date()
const year:number=date.getFullYear()
console.log('',year);
const month:number=date.getMonth()+1
console.log('',month);
const day:number=date.getDate()
console.log('',day);

@Entry
@Component
struct Index {
  build() {
    Column(){
    }
    }
}

image.png

值得一提的是在获取月份信息时需要对获取数据进行加一操作,这是由于getMonth() 方法返回的月份是从 0 开始的(0 表示 1 月,1 表示 2 月,依此类推),因此我们需要加 1 来获取实际的月份。

UTC

UTC(协调世界时,Coordinated Universal Time)是一种国际标准时间,它是全球时间的基准。以下是关于 UTC 的一些重要点:

特点
  1. 时区基准:UTC 不受任何时区的影响,是全球协调时间的基础。其他时区的时间是相对于 UTC 的偏移量,例如:

    • UTC+0(即 UTC 本身)
    • UTC+8(如中国标准时间,CST)
    • UTC-5(如美国东部时间,EST)
const date:Date=new Date()
const hour:number=date.getHours()
console.log('',hour);
const UTChour:number=date.getUTCHours()
console.log('',UTChour);
@Entry
@Component
struct Index {
  build() {
    Column(){
    }
    }
}

image.png