Date是ArkTs中一个常用的内置对象,他可以用来创建、解析、操作日期和时间。
使用 Date 对象首先需要通过 new 操作符进行实例化。
// 获取当前日期
const date1: Date = new Date()
// 获取指定日期
// ISO 8601 格式(YYYY-MM-DDTHH:mm:ss.ssZ)中间用 T 分隔
const date2: Date = new Date('1995-01-01T01:11:00')
// Unix时间戳 是指从1970年1月1日(UTC)开始到现在经历的时间(毫秒)
const date3: Date = new Date(1706170405708)
常用方法
方法名 | 作用 | 说明 | ||
getFullYear | 获取年份 | 4 位数年份 | ||
getMonth | 获取月份 | 取值 0-11 | ||
getDate | 获取日期 | 月份中的日期 | ||
getHours | 获取小时 | 无 | ||
getMinutes | 获取分钟 | 无 | ||
getSeconds | 获取秒 | 无 | ||
getDay | 获取星期 | 周日为 0 |
静态方法
方法名 | 作用 | 说明 | ||
now | 获取当前时间 | 时间戳 |
console.log(Date.now()+'')
代码展示:
const date1:Date=new Date()//获取当前日期
@Entry
@Component
struct DatePage {
date2:string=new Date().getDate().toString()//获取月份中的日期
build() {
Column() {
Text(date1+'')
Text(this.date2+'')
}
.width('100%')
.height('100%')
}
}