将日期和时间字符串转换为特定格式的日期

Converting date and time strings to date in specific format

我正在开发 Android 应用程序。

我从 JSON 文件中获取日期字符串和时间字符串。

fecha_reporte = "2017-12-17" 

hora_reporte = "23:51:00"

我需要将两个字符串都转换成一个日期变量,然后我需要用它做一些计算。

这是我目前拥有的:

String fecha = fecha_reporte + " " + hora_reporte;

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd H:m:s");
String dateInString = fecha;

try {

    Date date2 = formatter.parse(dateInString);
    System.out.println(date2);
    System.out.println(formatter.format(date2));
    Log.d("DURACION","DURACION REPORTE: calculado: "+date2);

} catch (ParseException e) {
    e.printStackTrace();
}

输出是一个日期,但格式如下:

Sun Dec 17 23:51:00 GMT-07:00 2017

我需要以下格式:2017-12-17 23:51:00

java.time

您使用的是麻烦的旧日期时间 classes,现在已经过时了。避开他们。现在被 java.time classes.

取代

将您的输入字符串解析为 LocalDateTime,因为它们缺少有关时区或与 UTC 的偏移量的信息。

添加 T 以符合标准 ISO 8601 格式。

String input = "2017-12-17" + "T" + "23:51:00" ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

通过调用 toString 生成所需格式的字符串,并将中间的 T 替换为 SPACE。

ldt.toString().replace( "T" , " " ) ;

或者,使用 DateTimeFormatter class.

生成自定义格式的字符串

对于早期的 Android,请参阅 ThreeTen-BackportThreeTenABP 项目。