Converting date and time strings to date in specific format

时间:2017-12-18 08:06:50

标签: java android date datetime-format

I am working on an Android app.

I get a date String and a time string from a sqrt(R^2 - (L/2)^2) file.

JSON

I need to convert both strings into a date variable, then later I will need to make some calculations with it.

This is what I have so far:

fecha_reporte = "2017-12-17" 

hora_reporte = "23:51:00"

The output is a date, but with this format:

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

I need it with following format: Sun Dec 17 23:51:00 GMT-07:00 2017

1 个答案:

答案 0 :(得分:2)

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项目。