HarmonyOS如何操作时间?
·
ArkTS Date 对象的使用
ArkTS 中的 Date 对象用于处理日期和时间,API 与 TypeScript/JavaScript 基本一致。下面整理常用的创建方式、获取/设置方法、格式化、时间戳计算等。
一、创建 Date 对象
// 1. 当前时间
const now: Date = new Date()
// 2. 通过时间戳(毫秒)创建
const d1: Date = new Date(1700000000000)
// 3. 通过日期字符串创建(建议使用 ISO 8601 格式)
const d2: Date = new Date('2025-06-16T10:30:00')
// 4. 通过年、月、日、时、分、秒、毫秒创建
// 注意:月份从 0 开始,0 表示 1 月,11 表示 12 月
const d3: Date = new Date(2025, 5, 16, 10, 30, 0, 0) // 2025-06-16 10:30:00
二、获取日期时间
const d: Date = new Date()
d.getFullYear() // 年,例如 2025
d.getMonth() // 月,0-11(注意 +1 才是真实月份)
d.getDate() // 日,1-31
d.getDay() // 星期几,0-6(0 表示星期日)
d.getHours() // 时,0-23
d.getMinutes() // 分,0-59
d.getSeconds() // 秒,0-59
d.getMilliseconds() // 毫秒,0-999
d.getTime() // 时间戳(毫秒)
d.getTimezoneOffset()// 与 UTC 的时差(分钟)
UTC 版本(统一获取 UTC 时区数据):
d.getUTCFullYear()
d.getUTCMonth()
d.getUTCDate()
d.getUTCHours()
// ... 其他 getUTCXxx 同理
三、设置日期时间
const d: Date = new Date()
d.setFullYear(2026)
d.setMonth(0) // 设置为 1 月
d.setDate(1)
d.setHours(8)
d.setMinutes(30)
d.setSeconds(0)
d.setMilliseconds(0)
d.setTime(1700000000000) // 通过时间戳设置
四、获取时间戳
// 当前时间戳 注意是毫秒时间戳(推荐,无需创建对象)
const ts1: number = Date.now()
// 通过 Date 实例获取
const ts2: number = new Date().getTime()
// 一元加号写法
const ts3: number = +new Date()
五、格式化输出
const d: Date = new Date()
d.toString() // "Tue Jun 16 2026 10:30:00 GMT+0800"
d.toDateString() // "Tue Jun 16 2026"
d.toTimeString() // "10:30:00 GMT+0800"
d.toISOString() // "2026-06-16T02:30:00.000Z"(UTC 时间)
d.toJSON() // 同 toISOString,常用于 JSON.stringify
d.toLocaleString() // 按本地化格式输出
d.toLocaleDateString()
d.toLocaleTimeString()
自定义格式化(常用工具函数):
function formatDate(date: Date, fmt: string = 'yyyy-MM-dd HH:mm:ss'): string {
const pad = (n: number): string => n < 10 ? `0${n}` : `${n}`
return fmt
.replace('yyyy', `${date.getFullYear()}`)
.replace('MM', pad(date.getMonth() + 1))
.replace('dd', pad(date.getDate()))
.replace('HH', pad(date.getHours()))
.replace('mm', pad(date.getMinutes()))
.replace('ss', pad(date.getSeconds()))
}
console.log(formatDate(new Date())) // 2026-06-16 10:30:00
六、日期比较
Date 对象之间不能直接用 == 或 === 比较,需要转成时间戳:
const a: Date = new Date('2025-06-16')
const b: Date = new Date('2025-06-17')
if (a.getTime() === b.getTime()) { /* 相等 */ }
if (a.getTime() < b.getTime()) { /* a 在 b 之前 */ }
// 比较运算符 < > 也可以直接使用(隐式转为时间戳)
if (a < b) { /* a 在 b 之前 */ }
七、日期计算
// 1. 增加 N 天
const d: Date = new Date()
d.setDate(d.getDate() + 7) // 7 天后
// 2. 增加 N 小时
d.setHours(d.getHours() + 3)
// 3. 计算两个日期间隔(天)
function diffDays(d1: Date, d2: Date): number {
const ms: number = Math.abs(d2.getTime() - d1.getTime())
return Math.floor(ms / (1000 * 60 * 60 * 24))
}
// 4. 当天的 0 点和 23:59:59
const start: Date = new Date()
start.setHours(0, 0, 0, 0)
const end: Date = new Date()
end.setHours(23, 59, 59, 999)
八、Date.parse 与 Date.UTC
// 解析日期字符串为时间戳
const ts: number = Date.parse('2025-06-16T10:30:00') // number
// 根据 UTC 年月日构造时间戳
const utcTs: number = Date.UTC(2025, 5, 16, 10, 30, 0)
const utcDate: Date = new Date(utcTs)
九、在 ArkTS 中的注意事项
- 类型必须显式声明:ArkTS 强类型,建议每个变量加上
Date、number、string等类型注解。 - 月份从 0 开始:
new Date(2025, 5, 16)是 6 月不是 5 月,getMonth()取出的值需要+1才是真实月份。 - 时区问题:
new Date('2025-06-16')默认按 UTC 解析,new Date('2025-06-16T00:00:00')按本地时区解析,跨时区场景注意区分getXxx和getUTCXxx。 - 性能:高频获取当前时间戳直接使用
Date.now(),比new Date().getTime()更快。
十、常见使用场景
1. 倒计时
@Entry
@Component
struct CountDown {
@State remain: number = 0
private timerId: number = -1
private deadline: number = Date.now() + 60 * 1000 // 60 秒后
aboutToAppear(): void {
this.timerId = setInterval(() => {
this.remain = Math.max(0, this.deadline - Date.now())
if (this.remain === 0) {
clearInterval(this.timerId)
}
}, 1000)
}
aboutToDisappear(): void {
clearInterval(this.timerId)
}
build() {
Text(`剩余 ${Math.floor(this.remain / 1000)} 秒`)
}
}
2. 显示"几分钟前"
function timeAgo(date: Date): string {
const diff: number = Date.now() - date.getTime()
const minute: number = 60 * 1000
const hour: number = 60 * minute
const day: number = 24 * hour
if (diff < minute) return '刚刚'
if (diff < hour) return `${Math.floor(diff / minute)} 分钟前`
if (diff < day) return `${Math.floor(diff / hour)} 小时前`
return `${Math.floor(diff / day)} 天前`
}
更多推荐
所有评论(0)