中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
参考代码如下:
let dateStr = '' try { //取日期时间戳 systemDateTime.getCurrentTime(true, (error, time) => { if (error) { console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); return; } dateStr = time.toString(); }); } catch(e) { console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); }
微信扫码分享
import systemDateTime from '@ohos.systemDateTime'; import { BusinessError } from '@ohos.base'; @Entry @Component struct Index5 { @State timeStr: string = ''; build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Text(`当前时间:` + this.timeStr).fontSize(20).fontWeight(FontWeight.Bold) Button("get time") .width(100) .height(100) .onClick(() => { //同步方法获取系统时间戳 try { let time = systemDateTime.getTime(false) this.timeStr = this.getTimeToYYYYDDMMHHMMSS(time) } catch (e) { let error = e as BusinessError; console.info(`Failed to get time. message: ${error.message}, code: ${error.code}`); } }) }.width('100%').height('100%') } //将时间戳转换成日期格式 getTimeToYYYYDDMMHHMMSS(str: number): string { let time: string = ""; console.log(str.toString()) let date = new Date(str); console.log(JSON.stringify(date)) try { let year = date.getFullYear(); let month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1); let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); let min = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); // time = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + second; time = '' + year + month + day + hour + min + second; console.log(date + "转换===>" + time); AlertDialog.show({ message: str + "时间戳转===>" + time }) } catch (e) { console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); } return time; } }