HarmonyOS鸿蒙Next中Date和string之间如何相互转换
HarmonyOS鸿蒙Next中Date和string之间如何相互转换
设备信息:Mate60
API版本:Api12
DevEco Studio版本:5.0.3.910
问题描述:Date 和 string 之间如何相互转换
3 回复
你好,可以参考如下代码
```javascript
parseDate(dateStr?: String, pattern: String = "yyyyMMddHHmmssSSS"): Date | undefined {
if (!dateStr || dateStr == "0") {
return undefined;
}
let currDate: string = dateStr as string;
let strArray = Array.from(pattern);
let strLength = strArray.length;
if (strLength > 0) {
let isBreak = false;
let regStr = "";
let regReplace = "";
let regIndex = 1;
let currChar = "";
let currStr = "";
for (let i = 0; i < strLength; i++) {
let char = strArray[i];
if (i == 0) {
currChar = char;
}
if (char == currChar) {
currStr += char;
if (i != strLength - 1) {
continue;
}
}
if ("yyyy" == currStr) {
regStr += "(\\d{4})";
if (regIndex > 1) {
regReplace += "/";
}
regReplace += "$" + regIndex;
++regIndex;
} else if ("MM" == currStr || "dd" == currStr || "HH" == currStr || "mm" == currStr || "ss" == currStr) {
regStr += "(\\d{2})";
if (regIndex > 1) {
if ("MM" == currStr || "dd" == currStr) {
regReplace += "/";
} else if ("HH" == currStr) {
regReplace += " ";
} else if ("mm" == currStr || "ss" == currStr) {
regReplace += ":";
}
}
regReplace += "$" + regIndex;
++regIndex;
} else if ("SSS" == currStr) {
regStr += "(\\d{3})";
regReplace += ".$" + regIndex;
++regIndex;
} else {
isBreak = true;
break;
}
currChar = char;
currStr = char;
}
if (!isBreak) {
currDate = dateStr.replace(new RegExp(regStr), regReplace);
console.log('currDate===========' + currDate)
}
}
console.log('====================================>' + new Date(currDate))
return new Date(currDate);
}
更多关于HarmonyOS鸿蒙Next中Date和string之间如何相互转换的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,Date
和string
之间的相互转换可以通过ohos.utils
模块中的DateTime
类实现。DateTime
类提供了将日期对象转换为字符串以及将字符串解析为日期对象的方法。
-
将
Date
转换为string
: 使用DateTime
的toString()
方法,可以将Date
对象转换为指定格式的字符串。例如:let date = new DateTime(2023, 10, 1, 12, 30, 0); let dateString = date.toString("yyyy-MM-dd HH:mm:ss"); console.log(dateString); // 输出:2023-10-01 12:30:00
-
将
string
转换为Date
: 使用DateTime
的静态方法fromString()
,可以将指定格式的字符串解析为DateTime
对象。例如:let dateString = "2023-10-01 12:30:00"; let date = DateTime.fromString(dateString, "yyyy-MM-dd HH:mm:ss"); console.log(date); // 输出:DateTime对象,表示2023-10-01 12:30:00
通过DateTime
类,可以方便地在Date
和string
之间进行转换。
在HarmonyOS鸿蒙Next中,Date
和string
之间的转换可以通过以下方式实现:
-
Date转String: 使用
SimpleDateFormat
类来格式化日期为字符串。Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = sdf.format(date);
-
String转Date: 使用
SimpleDateFormat
类将字符串解析为日期。String dateString = "2023-10-01 12:00:00"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = sdf.parse(dateString);
确保处理时捕获可能的ParseException
异常。