简体   繁体   中英

How to format current string into a date/time format?

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.

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?

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 .

Try below code:

String dt = "2019-02-22T13:43:00Z";
SimpleDateFormat mainformat = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", Locale.getDefault());
mainformat.setTimeZone(TimeZone.getTimeZone("UTC"));

try {
    Date date1 = mainformat.parse(dt);
    String date_time = new SimpleDateFormat("dd-MMM-yyyy HH:mm", Locale.ENGLISH).format(date1);
    Log.e("Date Time", date_time); 
} catch (Exception e) {
    e.printStackTrace();
}

Output: 22-Feb-2019 13:43

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM