【问题标题】:DateTimeFormatter create pattern [duplicate]DateTimeFormatter 创建模式 [重复]
【发布时间】:2019-11-12 00:49:52
【问题描述】:

我有这个日期:2008-01-10T11:00:00-05:00(date, T(separator), time, offset)

我有这个:DateTimeFormatter.ofPattern("yyyy-MM-ddSEPARATORHH-mm-ssOFFSET")

我使用这个table 来创建我的模式。

但是,我不知道如何记下SEPARATOR(T) 和 OFFSET。

对于OFFSET存在这个:x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;,但不知道如何使用x获取-08:30

【问题讨论】:

  • 为什么不使用DateTimeFormatter.ISO_DATE_TIME
  • 有一个预定义的DateTimeFormatter.ISO_OFFSET_DATE_TIME。它只解析您提供的String
  • 我不知道。谢谢。
  • 正如@deHaar 所说,您可以使用内置的formatter ISO_OFFSET_DATE_TIME。为了更直接地回答您关于格式模式字母x 的问题,它在Offset X 和x 下,我引用:三个字母输出小时和分钟,带冒号,例如' +01:30'。 所以你需要xxx。对于分隔符:' 文本分隔符的转义。所以将T 括在引号中:'T'

标签: java datetime datetime-format datetime-parsing java-time


【解决方案1】:

这里有一个小例子,展示了如何解析您的 String 并接收偏移量:

public static void main(String[] args) {
    // this is what you have, a datetime String with an offset
    String dateTime = "2008-01-10T11:00:00-05:00";
    // create a temporal object that considers offsets in time
    OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateTime);
    // just print them in two different formattings
    System.out.println(offsetDateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
    System.out.println(offsetDateTime.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")));
    // get the offset from the object
    ZoneOffset zonedOffset = offsetDateTime.getOffset();
    // get its display name (a String representation)
    String zoneOffsetString = zonedOffset.getDisplayName(TextStyle.FULL_STANDALONE, Locale.getDefault());
    // and print the result
    System.out.println("The offset you want to get is " + zoneOffsetString);
}

请注意代码 cmets,他们解释了做了什么。在代码中间打印两次OffsetDateTime 只是为了展示如何处理单个日期时间对象以及不同的格式化程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2018-05-23
    • 2019-04-08
    相关资源
    最近更新 更多