1

I have a String with several dates, for example:

[20-Jul-2012 5:11:36,670 UTC PM, 20-Jul-2012 5:11:36,683 UTC PM]

How do I read this string and extract each date? I'm using the SimpleDateFormat class to create a regex.

SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss,SSS z a");

I've tried :

I've just did, to get the first one and it changes the format and the timezone:

ParsePosition parsePos = new ParsePosition(1);
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss,SSS z a");
System.out.println(format2.parse(entry.getValue().toString(), parsePos)) ;

Output : Fri Jul 20 06:11:36 BST 2012

1
  • are those dates separated by commas ?? Commented Jul 22, 2012 at 11:00

2 Answers 2

1

You can try:

 parsePos = new ParsePosition(1);
 while((date = format2.parse(yourString, parsePos)!=null){
      //use date
 }
Sign up to request clarification or add additional context in comments.

1 Comment

I've just did, to get the first one and it changes the timezone: ParsePosition parsePos = new ParsePosition(1); SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss,SSS z a"); Output : Fri Jul 20 06:11:36 BST 2012 System.out.println(format2.parse(entry.getValue().toString(), parsePos)) ;
1

java.time

The question uses SimpleDateFormat which was the correct thing to do in 2012. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern Date-Time API. Since then, it is strongly recommended to stop using the legacy date-time API.

Solution using the modern date-time API:

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;

class Main {
    public static void main(String[] args) {
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("d-MMM-uuuu h:m:s,SSS VV a", Locale.ENGLISH);
        Stream.of(
                    "20-Jul-2012 5:11:36,670 UTC PM",
                    "20-Jul-2012 5:11:36,683 UTC PM"
            )
            .map(s -> ZonedDateTime.parse(s, parser))
            .forEach(System.out::println);
    }
}

Output:

2012-07-20T17:11:36.670Z[UTC]
2012-07-20T17:11:36.683Z[UTC]

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.