简体   繁体   English

如何在 React Native 中将字符串格式化为日期?

[英]How to format a String to Date in React Native?

I am getting a Date as a String in this format from the server yyyyMMdd:hhmmss .我正在从服务器yyyyMMdd:hhmmss获取这种格式的Date String

Is there a generic way to format this string to a Date object?有没有一种通用的方法可以将此字符串格式化为Date对象?

EDIT编辑

 formatDate = (data) => {
    return data.slice(6, 8) + "." + data.slice(4, 6) + "." + data.slice(0, 4) + " " + data.slice(9, 11) + ":" + data.slice(11, 13)
}

The way you're reformatting the string is fine, even though it seems like a lot of code for a small job, slice is pretty fast.您重新格式化字符串的方式很好,即使看起来像一个小工作的很多代码,切片也非常快。 Some alternatives (not necessarily "better", just different):一些替代方案(不一定“更好”,只是不同):

 // Reformat yyyyMMdd:hhmmss as dd.mm.yyyy hh:mm:ss function formatMatch(s) { let b = s.match(/\\d\\d/g) || []; return `${b[3]}.${b[2]}.${b[0]}${b[1]} ${b[4]}:${b[5]}:${b[6]}`; } function formatReplace(s) { return s.replace(/(\\d{4})(\\d{2})(\\d{2}):(\\d{2})(\\d{2})(\\d{2})/, '$3.$2.$1 $4:$5:$6'); } formatDate = (data) => { return data.slice(6, 8) + "." + data.slice(4, 6) + "." + data.slice(0, 4) + " " + data.slice(9, 11) + ":" + data.slice(11, 13) } let s = '20200323:123445'; console.log(formatDate(s)); console.log(formatMatch(s)); console.log(formatReplace(s));

If you want to get an actual Date object, then instead of using the bits to create another string, just pass them into the constructor:如果你想获得一个实际的 Date 对象,那么不要使用这些位来创建另一个字符串,只需将它们传递给构造函数:

 // Parse yyyyMMdd:hhmmss to Date object function parseD(s) { let b = s.match(/\\d\\d/g) || []; return new Date(b[0]+b[1], b[2]-1, b[3], b[4], b[5], b[6]); } let s = '20200327:134523'; console.log(parseD(s).toString());

The use of || [] || []的使用|| [] means that if there's no match, an empty array is returned so all the b[*] terms return undefined and the result is an invalid date. || []表示如果没有匹配项,则返回一个空数组,因此所有b[*]项都返回undefined并且结果是无效日期。

The above uses match , but slice or substring can be used the same way.上面使用了match ,但是slicesubstring可以以相同的方式使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM