代码之家  ›  专栏  ›  技术社区  ›  masterfly

将字符串转换为即时

  •  49
  • masterfly  · 技术社区  · 7 年前

    我试图使用java 8或UTIL包将字符串中的datetime转换为instant。

    对于eg。

    String requestTime = "04:30 PM, Sat 5/12/2018";
    

    Instant reqInstant should result in 2018-05-12T20:30:00.000Z
    

    reqString位于美国/多伦多时区。

    这就是我试过的

     String strReqDelTime = "04:30 PM, Sat 5/12/2018";
     Date date = new SimpleDateFormat("hh:mm a, EEE MM/dd/yyyy").parse(requestTime);
     Instant reqInstant = date.toInstant();
    

    上述代码导致 "2018-05-12T23:30:00Z"

    非常感谢您的帮助。

    4 回复  |  直到 7 年前
        1
  •  90
  •   Basil Bourque    7 年前

    tl;博士

    • 修复未添加月份的格式模式(&A);白天
    • 仅使用 JAVA时间 类,而不是遗留类。

    人为示例:

    LocalDateTime.parse(                   // Parse as an indeterminate `LocalDate`, devoid of time zone or offset-from-UTC. NOT a moment, NOT a point on the timeline.
        "04:30 PM, Sat 5/12/2018" ,        // This input uses a poor choice of format. Whenever possible, use standard ISO 8601 formats when exchanging date-time values as text. Conveniently, the java.time classes use the standard formats by default when parsing/generating strings.
        DateTimeFormatter.ofPattern( "hh:mm a, EEE M/d/uuuu" , Locale.US )  // Use single-character `M` & `d` when the number lacks a leading padded zero for single-digit values.
    )                                      // Returns a `LocalDateTime` object.
    .atZone(                               // Apply a zone to that unzoned `LocalDateTime`, giving it meaning, determining a point on the timeline.
        ZoneId.of( "America/Toronto" )     // Always specify a proper time zone with `Contintent/Region` format, never a 3-4 letter pseudo-zone such as `PST`, `CST`, or `IST`. 
    )                                      // Returns a `ZonedDateTime`. `toString` → 2018-05-12T16:30-04:00[America/Toronto].
    .toInstant()                           // Extract a `Instant` object, always in UTC by definition.
    .toString()                            // Generate a String in standard ISO 8601 format representing the value within this `Instant` object. Note that this string is *generated*, not *contained*.
    

    2018-05-12T20:30:00Z

    使用一位数格式模式

    您使用 MM 在您的格式模式中,表示任何一个数字值(月份1月至9月)都将以填充的前导零显示。

    但您的输入缺少填充的前导零。因此,请使用单个 M

    我预计月日也是如此: d 而不是 dd

    仅使用 JAVA时间

    您正在使用有缺陷的旧日期时间类( Date & SimpleDateFormat )多年前被 课程。新课程完全取代旧课程。没有必要将传统与现代混为一谈。

    LocalDateTime

    解析为 LocalDateTime 因为您的输入字符串缺少 time zone offset-from-UTC .该值为 等一下,是 时间线上的一点。它只是一套 潜在的 力矩范围约为26-27小时。

    String input = "04:30 PM, Sat 5/12/2018";
    DateTimeFormatter f = DateTimeFormatter.ofPattern( "hh:mm a, EEE M/d/uuuu" , Locale.US );  // Specify locale to determine human language and cultural norms used in translating that input string.
    LocalDateTime ldt = LocalDateTime.parse( input , f );
    

    ldt。toString():2018-05-12T16:30

    ZonedDateTime

    如果您确定输入的目的是使用多伦多-加拿大地区的人使用的挂钟时间来表示某一时刻,请应用 ZoneId 获取 ZonedDateTime 对象

    指定时区会使未分区的 LocalDateTime 现在我们有一个时刻,时间线上的一个点。

    ZoneId z = ZoneId.of( "America/Toronto" ) ;
    ZonedDateTime zdt = ldt.atZone( z ) ;  // Give meaning to that `LocalDateTime` by assigning the context of a particular time zone. Now we have a moment, a point on the timeline.
    

    zdt。toString():2018-05-12T16:30-04:00[美国/多伦多]

    Instant

    看到与 UTC ,提取 Instant .相同的时刻,不同的挂钟时间。

    Instant instant = zdt.toInstant() ;
    

    瞬间toString():2018-05-12T20:30:00Z


    关于 JAVA时间

    这个 java.time 框架内置于Java 8及更高版本中。这些课程取代了烦人的旧课程 legacy 日期时间类,如 java.util.Date ,则, Calendar ,& SimpleDateFormat

    这个 Joda-Time 项目,现在处于 maintenance mode ,建议迁移到 java.time 课程。

    要了解更多信息,请参阅 Oracle Tutorial 。并搜索堆栈溢出以获取许多示例和解释。规格为 JSR 310

    您可以交换 JAVA时间 对象直接与数据库连接。使用 JDBC driver 符合 JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 课程。

    从何处获取java。时间课程?

    这个 ThreeTen-Extra project扩展了java。额外上课的时间。该项目是java未来可能添加内容的试验场。时间您可以在这里找到一些有用的类,例如 Interval ,则, YearWeek ,则, YearQuarter more

        2
  •  2
  •   Upperstage    3 年前

    您的计算机(服务器)中的时区似乎是美国太平洋夏令时(GMT-7),但您希望得到美国东部夏令时(GMT-4)的结果。

    瞬间toString()以ISO-8601格式返回UTC(GMT+0)日期时间。(“Z”在末尾表示UTC)。

    SimpleDataFormat在未指定计算机的默认时区中处理DateTime字符串。并且您的输入没有指定时区。

    因此,您需要对输入的时区做些什么。

    另外,在东部夏令时的我的机器上,你的代码给出的结果和你预期的完全一样。

        3
  •  0
  •   Shila Mosammami    3 年前

    有关说明,请参见此处[https://www.baeldung.com/java-string-to-date]

    String requestTime = "04:30 PM, Sat 5/12/2018 America/Toronto";
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a, EEE M/dd/yyyy z");
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(requestTime, formatter);
                System.out.println(zonedDateTime.toInstant());  
    
        4
  •  0
  •   Andrea Paolo Ferraresi    3 年前

    瞬间正确格式化解析(字符串)