【问题标题】:Convert date and time to timestamp format java "2019-02-21T14:10:18.161+0000"将日期和时间转换为时间戳格式 java "2019-02-21T14:10:18.161+0000"
【发布时间】:2019-09-11 13:47:31
【问题描述】:

我需要将这个时间和日期转换成这个时间戳格式:
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);

【问题讨论】:

  • 您的isoDatePattern 与您尝试使用它解析的实际输入格式不同。

标签: java android timestamp simpledateformat


【解决方案1】:

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

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

【讨论】:

  • 它工作正常,谢谢@Christian。我的输出:E/dateString ::::>: 2019-04-22T10:04:30.000+0100
  • 这些糟糕的日期时间类在几年前被 JSR 310 的采用所取代。改用 java.time 类。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    鉴于您要解析的日期字符串,您需要:

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

    【讨论】:

    • 不知道为什么。没有规定所有日期格式都必须符合 ISO 8601(也许这是最佳实践),但这不是 OP 的要求。
    • 我明白了,我只是粘贴了 OP 的代码,并没有检查变量名。固定。
    • @BasilBourque 已修复。
    猜你喜欢
    • 2016-11-26
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多