1

Is there a way to find the date anywhere in a timestamp? For example,

2017-01-31 01:33:30 random text log message x

where the data is in the beginning of the string or:

01:33:30 2017-01-31 random text log message x

where the date is in the middle. How could you parse every string to get the date in java?

Demetrius
  • 449
  • 1
  • 9
  • 20

2 Answers2

6

Yes, you can use regex as below to retrieve the date.

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
}
Jonathan Gagne
  • 4,241
  • 5
  • 18
  • 30
1

Regex is overkill

No need for tricky regex matching here. Just parse the date-time text as date-time objects.

java.time

In your example, only two formats are used. So attempt to parse each using the modern java.time classes. They are similar, one is date-first, the other is time-of-day first.

DateTimeFormatter fDateTime = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
DateTimeFormatter fTimeDate = DateTimeFormatter.ofPattern( "HH:mm:ss uuuu-MM-dd" ) ;

First, extract the first 19 characters from your string, to focus only on the date-time data.

Parse, trapping for the 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. 
}

If you want the date-only without the time-of-day, extract a LocalDate object.

LocalDate ld = ldt.toLocalDate() ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154