【问题标题】:Java SimpleDateFormat not detecting month [duplicate]Java SimpleDateFormat 未检测到月份 [重复]
【发布时间】:2020-03-08 11:55:42
【问题描述】:

我在 Java 中使用 SimpleDateFormat,由于某种原因它没有检测到月份。这是我的代码:

     /**
     * Takes a date/time stamp which looks like yyyyMMDDhhmmss on converts it to
     * yyyy-MM-DDThh:mm:ssZ
     *
     * @param timestamp
     * @return
     */
    public static String ConvertDate(String timestamp) {
        if (timestamp == null || timestamp.length() < 14)
            return null;

        String timeString = null;

        System.out.println(timestamp);
        DateFormat outputFormat = new SimpleDateFormat("YYYY-MM-DD'T'hh:mm:ss'Z'");
        DateFormat inputFormat = new SimpleDateFormat("yyyyMMDDhhmmss");

        try{
            Date date = inputFormat.parse(timestamp);
            timeString = outputFormat.format(date);
        }
        catch(Exception e){}

        return timeString;
    }

调用此方法:ConvertDate("20190803122424") 返回以下内容:2019-01-03T12:24:24Z 而我想返回:2019-08-03T12:24:24Z

我的输出格式有问题吗?

【问题讨论】:

  • 你试过把“yyyyMMDDhhmmss”改成“yyyyMMddHHmmss”(小写D,大写H)吗?
  • 值得注意的是,在这种情况下调用setLenient(false) 会导致parse 抛出异常。
  • 我建议你不要使用SimpleDateFormatDate。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APIOffsetDateTimeDateTimeFormatter
  • 不仅您的输入格式,您的输出格式模式字符串也有几个错误大小写的模式字母实例。此外,带引号的'Z' 必然会给您带来不正确的结果。

标签: java simpledateformat date-format


【解决方案1】:

您使用了错误的日期格式字符串:DD(年中的日)而不是dd(月中的日)。将两个SimpleDateFormat 实例都更改为使用dd

DateFormat inputFormat = new SimpleDateFormat("yyyyMMddhhmmss");
DateFormat outputFormat = new SimpleDateFormat("YYYY-MM-dd'T'hh:mm:ss'Z'");

因此你得到了错误的结果。

【讨论】:

  • 给魔鬼应得的,你更快
  • 这样做返回了正确的月份但搞砸了一天:2019-08-215T12:24:24Z
  • @Smi28 这是输出格式化程序的问题,而不是日期解析器的问题。
  • 您还在输出格式化程序中使用了DD。在这两种情况下你都需要dd
【解决方案2】:

正如每个人都指出您的格式化程序 yyyyMMDDhhmmss 是错误的,所以使用有效格式创建 DateTimeFormatter

DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

并通过使用 java-8 日期时间 API 将其解析为 LocalDateTime,然后使用 ZonedDateTime 解析为 UTC 格式

String dateString = "20190803122424";

LocalDateTime localDateTime = LocalDateTime.parse(dateString,inputFormat);

然后你就可以把它转换成OffsetDateTime

 OffsetDateTime outputDateTime = localDateTime.atOffset(ZoneOffset.UTC);

如果你特别想要ZonedDateTime

ZonedDateTime outputDateTime = localDateTime.atZone(ZoneOffset.UTC);

【讨论】:

  • 谢谢我更新了使用OffsetDateTime@BasilBourque的方法
  • 感谢您的想法,但无需归功于我。我建议用OffsetDateTime 完全替换您的ZonedDateTime 行。另外,为了清楚起见,我建议将您的 LocalDateTime 对象分成自己的行。所以两行:LocalDateTime localDateTime = …OffsetDateTime offsetDateTime = …
猜你喜欢
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
相关资源
最近更新 更多