我正在开发 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
您正在使用麻烦的旧日期时间类,这些类现在已经成为遗留问题。避开他们。现在被 java.time 类取代。
将您的输入字符串解析为 LocalDateTime
,因为它们缺少有关时区或与 UTC 的偏移量的信息。
添加 T
以符合标准 ISO 8601 格式。
String input = "2017-12-17" + "T" + "23:51:00" ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
通过调用 toString
生成所需格式的字符串,并将中间的 T
替换为空格。
ldt.toString().replace( "T" , " " ) ;
或者,使用 DateTimeFormatter
类生成自定义格式的字符串。
对于早期的 Android,请参阅 ThreeTen-Backport 和 ThreeTenABP项目。
关于java - 将日期和时间字符串转换为特定格式的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47864295/