将日期和时间转换为时间戳格式的java "2019-02-21T14:10:18.161+0000"



我需要将此时间和日期转换为此时间戳格式:
2019/04/22 10:04:30 至 2019-02-21T14:10:18.161+0000

这是我的代码,它不起作用,我错过了一些东西,对吧?

String isoDatePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(isoDatePattern);
Date d = null;
try {
    d = simpleDateFormat.parse("2019/04/22 10:04:30");
} 
catch (ParseException e) {
    e.printStackTrace();
}
String dateString = simpleDateFormat.format(d);
Log.e("dateString ::::> ",dateString);

您尝试使用输出格式分析输入。未经测试:

String isoInputDatePattern = "yyyy/MM/dd HH:mm:ss";
SimpleDateFormat simpleInputDateFormat = new SimpleDateFormat(isoInputDatePattern);
String isoOutputDatePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
SimpleDateFormat simpleOutputDateFormat = new SimpleDateFormat(isoOutputDatePattern);
Date d = null;
try {
   d = simpleInputDateFormat.parse("2019/04/22 10:04:30");
} catch (ParseException e) {
   e.printStackTrace();
}
String dateString = simpleOutputDateFormat.format(d);
Log.e("dateString ::::> ",dateString);

您需要两种格式:用于解析日期的格式,以及用于格式化所需的日期格式。

给定您尝试解析的日期字符串,您需要:

String datePattern = "yyyy/MM/dd HH:mm:ss";

对于模式。

不过,您可能应该考虑使用 Java 8 日期/时间:

String str = "2019/04/22 10:04:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

最新更新