Hi I am having a small code snippet. I am trying to parse the date-time string that does not contain minutes 2019-10-12T07Z.
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class App
{
public static void main( String[] args )
{
// 2019-10-12T07:00:00Z
OffsetDateTime offSetDateTime = OffsetDateTime.parse("2019-10-12T07Z");
System.out.println(offSetDateTime.format(DateTimeFormatter.ISO_DATE_TIME));
}
}
when i runs the above code it throws the following exception stack trace
Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-10-12T07Z' could not be parsed at index 13
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.OffsetDateTime.parse(OffsetDateTime.java:402)
at java.time.OffsetDateTime.parse(OffsetDateTime.java:387)
at com.test.offset.offset.App.main(App.java:16)
Expected output
2019-10-12T07:00:00Z
any idea what should i do ? appreciate if yoiu can help
CodePudding user response:
You have to create custom DateTimeFormatter representing the time and offset.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HHX");
OffsetDateTime odt = OffsetDateTime.parse("2019-10-12T07Z",formatter) ;
System.out.println( odt ); //2019-10-12T07:00Z
See that code run at Ideone.com.
2019-10-12T07:00Z
If you want to display the seconds, extract an Instant
to use its toString
method.
Instant instant = odt.toInstant() ;
System.out.println( instant ) ; // 2019-10-12T07:00:00Z
2019-10-12T07:00:00Z
CodePudding user response:
This is what I usually do when I need date timestamp
String dateFile = new SimpleDateFormat("MM-dd-yyyy").format(new java.util.Date());
String timeFile = new SimpleDateFormat("HH-mm").format(new java.util.Date());