Java 正则表达式截断时间戳值
Java Regular Expression Truncate Timestamp value
Input : 2007-02-09 00:00:00.0
Expected : 2007-02-09
我们如何使用 Java 正则表达式截断 00:00:00.0
?
提示:
- Use
indexOf([space])
and substring(index+1)
methods (no regex needed).
如果您热衷于使用正则表达式:
String#replaceAll()
--> capture everything until the space and then replace everything with the captured group.
试试这个:
String s = "2007-02-09 00:00:00.0";
System.out.println(s.replaceAll("\s\d{2}:\d{2}:\d{2}\.\d*", ""));
这会将时间部分替换为空,因此您会得到预期的结果。
你可以做到
String a="2007-02-09 00:00:00.0";
String b=a.split("\s")[0];
System.out.println(b); // 2007-02-09
您也可以使用SimpleDateForMat
String a = "2007-02-09 00:00:00.0";
Date myDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(a);
System.out.println(myDate);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(myDate);
System.out.println(formattedDate); // 2007-02-09
Input : 2007-02-09 00:00:00.0
Expected : 2007-02-09
我们如何使用 Java 正则表达式截断 00:00:00.0
?
提示:
- Use
indexOf([space])
andsubstring(index+1)
methods (no regex needed).
如果您热衷于使用正则表达式:
String#replaceAll()
--> capture everything until the space and then replace everything with the captured group.
试试这个:
String s = "2007-02-09 00:00:00.0";
System.out.println(s.replaceAll("\s\d{2}:\d{2}:\d{2}\.\d*", ""));
这会将时间部分替换为空,因此您会得到预期的结果。
你可以做到
String a="2007-02-09 00:00:00.0";
String b=a.split("\s")[0];
System.out.println(b); // 2007-02-09
您也可以使用SimpleDateForMat
String a = "2007-02-09 00:00:00.0";
Date myDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(a);
System.out.println(myDate);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(myDate);
System.out.println(formattedDate); // 2007-02-09