猿问

在时间戳中的任何位置查找日期

有没有办法在时间戳的任何地方找到日期?例如,

2017-01-31 01:33:30 随机文本日志消息 x

其中数据位于字符串的开头或:

2017-01-31 01:33:30 随机文本日志消息 x

日期在中间。您如何解析每个字符串以获取 java 中的日期?


Helenr
浏览 128回答 2
2回答

互换的青春

是的,您可以使用下面的正则表达式来检索日期。Pattern p = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");Matcher m = p.matcher("2017-01-31 01:33:30 random text log message x");if (m.find()) {    System.out.println(m.group(1)); //print out the date}

呼啦一阵风

正则表达式是矫枉过正这里不需要棘手的正则表达式匹配。只需将日期时间文本解析为日期时间对象。java.time在您的示例中,仅使用了两种格式。所以尝试使用现代的java.time类来解析每一个。它们是相似的,一个是日期优先,另一个是时间优先。DateTimeFormatter fDateTime = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;DateTimeFormatter fTimeDate = DateTimeFormatter.ofPattern( "HH:mm:ss uuuu-MM-dd" ) ;首先,从字符串中提取前 19 个字符,只关注日期时间数据。解析,为DateTimeParseException.LocalDateTime ldt = null ;try{    if( Objects.isNull( ldt ) {        LocalDateTime ldt = LocalDateTime.parse( input , fDateTime ) ;    }} catch ( DateTimeParseException e ) {    // Swallow this exception in this case.}try{    if( Objects.isNull( ldt ) {        LocalDateTime ldt = LocalDateTime.parse( input , fTimeDate ) ;    }} catch ( DateTimeParseException e ) {    // Swallow this exception in this case.}// If still null at this point, then neither format above matched the input.if( Objects.isNull( ldt ) {    // TODO: Deal with error condition, where we encountered data in unexpected format. }如果您想要没有时间的仅日期,请提取一个LocalDate对象。LocalDate ld = ldt.toLocalDate() ;
随时随地看视频慕课网APP

相关分类

Java
我要回答