如何将当前字符串格式化为 date/time 格式?

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

我正在尝试将此字符串转换为 date/time 格式
我正在从数据库中获取此字符串,只是想将其转换为正确的日期和时间...
String str = 2019-02-22T13:43:00Z;//输入
我通过以下代码从该字符串中获取正确的日期:

 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);  

在上面的代码中(date_time = 22-Feb-2019 12:00)即将到来。
预期输出为:2019 年 2 月 22 日 13:43
这里的问题是我无法从该默认格式获得正确的时间。

试试下面的代码:

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

现代方法使用 java.time 类.

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 ) ;

输出:

22-Feb-2019 13:43

关于java.time

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.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

Joda-Time project, now in maintenance mode, advises migration to the java.time 类.

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类.

在哪里获取java.time类?

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.