时间戳如何转换为xxxx年xx月xx日的字符串 HarmonyOS 鸿蒙Next

时间戳如何转换为xxxx年xx月xx日的字符串 HarmonyOS 鸿蒙Next 需要一个时间戳转换为xxxx年xx月xx日的字符串的方法

4 回复
let date = new Date(1740128049264);
let dateFormat1 = new intl.DateTimeFormat('zh-CN', { dateStyle: 'full', timeStyle: 'full' });
let formattedDate1 = dateFormat1.format(date); // formattedDate1: 2025年2月21日星期五 中国标准时间 16:54:09

更多关于时间戳如何转换为xxxx年xx月xx日的字符串 HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


如下代码参考一下

let getDateStringWithTimeStamp = (timestamp: number): string => {
    let date = new Date(timestamp);
    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2);
    const day = ("0" + date.getDate()).slice(-2);
    let formattedDate = `${year}年${month}月${day}日`
    return formattedDate
}

引入dayjs库

https://ohpm.openharmony.cn/#/cn/detail/dayjs

ohpm i dayjs

dayjs().format('YYYY-MM-DD')

更多dayjs用法可看这个

https://dayjs.fenxianglu.cn/category/parse.html#%E5%AE%9E%E4%BE%8B

在HarmonyOS鸿蒙Next中,可以使用DateTime类进行时间戳到字符串的转换。以下是一个示例代码,展示如何将时间戳转换为“xxxx年xx月xx日”格式的字符串:

import DateTime from '@ohos.i18n';

// 假设时间戳为毫秒级
let timestamp = 1633072800000;

// 创建DateTime对象
let dateTime = new DateTime.DateTime(timestamp);

// 设置日期格式
let options = { year: 'numeric', month: '2-digit', day: '2-digit' };

// 转换为字符串
let dateString = dateTime.format(options);

console.log(dateString); // 输出格式为 "2021年10月01日"

此代码通过DateTime类将时间戳格式化为指定格式的字符串。options对象定义了所需的时间格式,format方法根据这些选项生成字符串。

回到顶部