開發(fā)中常見的時(shí)間與時(shí)間戳間相互轉(zhuǎn)換的需要,如下是基于系統(tǒng) api 的 import systemDateTime from '@ohos.systemDateTime'; 實(shí)現(xiàn);
具體實(shí)現(xiàn)如下:
import systemDateTime from '@ohos.systemDateTime'
/*公共方法類*/
export class PublicUtils {
/**
* 時(shí)間戳轉(zhuǎn)時(shí)間
* PublicUtils.getDateTime(systemDateTime.getTime(), 'yyyy-MM-dd HH:mm:ss')
* @param time 時(shí)間戳(默認(rèn)獲取當(dāng)前時(shí)間)
* @param type 時(shí)間格式(默認(rèn)'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)
}
// 獲取時(shí)間
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()
// 補(bǔ)位
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
// 默認(rèn)格式:年月日
type = type ? type : 'yyyy-MM-dd'
// 格式轉(zhuǎn)換
let timeStr = `${year}-${month}-${day}` // 默認(rèn) 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
}
}
以上便是此次分享的全部?jī)?nèi)容改艇,希望能對(duì)大家有所幫助!