简体   繁体   English

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

[英]Converting date and time strings to date in specific format

I am working on an Android app. 我正在开发一个Android应用程序。

I get a date String and a time string from a JSON file. 我从JSON文件中获得了日期字符串和时间字符串。

fecha_reporte = "2017-12-17" 

hora_reporte = "23:51:00"

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: 这是我到目前为止的内容:

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

The output is a date, but with this format: 输出为日期,但格式如下:

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

I need it with following format: 2017-12-17 23:51:00 我需要使用以下格式: 2017-12-17 23:51:00

java.time java.time

You are using troublesome old date time classes that are now legacy. 您正在使用麻烦的旧日期时间类,这些类现在是旧的。 Avoid them. 避免他们。 Now supplanted by the java.time classes. 现在由java.time类取代。

Parse your input strings as LocalDateTime as they lack information about time zone or offset-from-UTC. 将输入字符串解析为LocalDateTime因为它们缺少有关时区或UTC偏移量的信息。

Add a T to comply with standard ISO 8601 format. 添加一个T以符合标准ISO 8601格式。

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

Generate a String in your desired format by calling toString and replace the T in the middle with a SPACE. 通过调用toString生成所需格式的String并将中间的T替换为SPACE。

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

Alternatively, generate strings in custom formats using DateTimeFormatter class. 或者,使用DateTimeFormatter类以自定义格式生成字符串。

For earlier Android, see the ThreeTen-Backport and ThreeTenABP projects. 对于早期的Android,请参见ThreeTen- BackportThreeTenABP项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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