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
You can try:
parsePos = new ParsePosition(1);
while((date = format2.parse(yourString, parsePos)!=null){
//use date
}
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]
Learn more about the modern Date-Time API from Trail: Date Time .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.