HarmonyOS 鸿蒙Next 我有秒级时间戳 ,怎么根据传入的formatStr 输出时间字符串?
HarmonyOS 鸿蒙Next 我有秒级时间戳 ,怎么根据传入的formatStr 输出时间字符串?
我有秒级时间戳 ,怎么根据传入的fortmatStr 输出时间字符串?fortmatStr 可以自定义,比如yyyy-MM-dd
2 回复
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}`);
}
//异步方法获取系统时间戳
try {
systemDateTime.getCurrentTime(false, (error, time) => {
if (error) {
console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`)
return;
}
console.info(`Succeeded in getting currentTime : ${time}`);
this.timeStr = this.getTimeToYYYYDDMMHHMMSS(time)
})
AlertDialog.show({ message: 'sss' });
} catch (e) {
console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.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;//如果需要yy-mm-dd的格式,请将hour,min,second删除
console.log(date + "转换===>" + time);
} catch (e) {
console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`);
}
return time;
}
}
第二种使用第三方库dayjs,完整代码如下:
//三方库days的下载使用参考链接:
//https://gitee.com/openharmony-tpc/openharmony_tpc_samples/tree/master/dayjs
import dayjs from "dayjs";
@Entry
@Component
struct Index {
@State timeStr : number = 1318781876;
@State timeNow: string = ''
build() {
Row() {
Column() {
Text(`当前时间:`+this.timeNow)
.fontSize(20)
.fontWeight(FontWeight.Bold)
.width("100%")
Button("get time")
.onClick(() => {
try {
this.timeNow = this.getTimeToYYYYDDMMHHMMSS(this.timeStr)
}
catch (e) {
}
})
}
.justifyContent(FlexAlign.Center)
.width('100%')
}
.height('100%')
}
getTimeToYYYYDDMMHHMMSS(str: number): string {
let time:string =''
time = dayjs.unix(1318781876).format('YYYY-MM-DD HH:mm:ss')
return time
}
}
更多关于HarmonyOS 鸿蒙Next 我有秒级时间戳 ,怎么根据传入的formatStr 输出时间字符串?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next系统中,你可以使用Java或JavaScript(取决于你的开发环境)来处理时间戳并格式化为指定的字符串。以下是基于Java的示例代码,展示如何根据传入的格式字符串formatStr
将秒级时间戳转换为时间字符串:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TimeUtils {
public static String formatTimestamp(long timestampInSeconds, String formatStr) {
// 将秒级时间戳转换为毫秒级
long timestampInMillis = timestampInSeconds * 1000L;
// 创建SimpleDateFormat对象并设置时区(如果需要)
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
sdf.setTimeZone(TimeZone.getDefault()); // 可根据需要设置其他时区
// 格式化时间戳
return sdf.format(new Date(timestampInMillis));
}
public static void main(String[] args) {
long timestamp = 1696272000L; // 示例时间戳
String formatStr = "yyyy-MM-dd HH:mm:ss";
String formattedDate = formatTimestamp(timestamp, formatStr);
System.out.println(formattedDate);
}
}
这段代码将秒级时间戳转换为毫秒级,然后使用SimpleDateFormat
根据传入的格式字符串formatStr
进行格式化。如果formatStr
是有效的日期时间格式模式,这段代码就能正确输出格式化后的时间字符串。
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html