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

Convert date and time to timestamp format java "2019-02-21T14:10:18.161+0000"

我需要将这个时间和日期转换成这个时间戳格式:
2019/04/22 10:04:302019-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 datePattern = "yyyy/MM/dd HH:mm:ss";

为了图案。

您可能应该考虑使用 Java 8 date/time 而不是:

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

您需要两种格式:您拥有的日期格式,用于解析它,以及您想要的日期格式,用于重新格式化。

您尝试用输出格式解析输入。未测试:

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