I am trying to convert this String into date/time format
I am getting this string from the database and just want to convert it into proper date and time…
String str = 2019-02-22T13:43:00Z;//input
I am getting proper date from this string by this code:
String[] split_date = date_time.split("T",2); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = format.parse ( split_date[0]); date_time = new SimpleDateFormat("dd-MMM-yyyy hh:mm", Locale.ENGLISH).format(date1);
In above code (date_time = 22-Feb-2019 12:00) is coming.
expected output is : 22-feb-2019 13:43
The problem here is I can’t get the proper time from that default format.
Answer
The modern approach uses the java.time classes.
Instant instant = Instant.parse( "2019-02-22T13:43:00Z" ) ; OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ; DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu HH:mm" ) ; String output = odt.format( f ) ;
output :
22-Feb-2019 13:43
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later – Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.