有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Year在dateTimeFormat之后更改为0000

我正在尝试将日期时间从字符串转换为组织。乔达。时间LocalDateTime。下面代码中的变量actualLocalDateTime设置为:0000-03-05T14:00:09.000,而不是2020-03-05T14:00:09.000。 我错过了什么

DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.xxxx");
String dateTimeString = "2020-03-05 14:00:09.000000";
LocalDateTime actualLocalDateTime = DATE_TIME_FORMATTER.parseLocalDateTime(dateTimeString);

共 (3) 个答案

  1. # 1 楼答案

    weekyear

     Symbol  Meaning                      Presentation  Examples
             -                                 -
     x       weekyear                     year          1996
    

    您使用xxxx来解析似乎是秒分数的内容。模式字母x表示基于周的年份。既然分数是0,你就把年份设为0

    解决方法:使用SSSSSS表示秒的分数,而不是xxxx,如Sanjay的正确答案所示

    S       fraction of second           millis        978
    

    文档中说是毫秒(所以是毫秒),但是解析.000000(微秒)也有效。您需要指定小数的确切数目,所以SSSSSS。当发生这种情况时,Joda Time会将前三位小数用于毫秒,而忽略其余的小数

    链接:Documentation of ^{}

  2. # 2 楼答案

    乔达时代图书馆

            org.joda.time.format.DateTimeFormatter USPS_DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
            String dateTimeString = "2020-03-05 14:00:09.000000";
            org.joda.time.LocalDateTime actualLocalDateTime = USPS_DATE_TIME_FORMATTER.parseLocalDateTime(dateTimeString);
            System.out.println(actualLocalDateTime);
    
  3. # 3 楼答案

    正如在前面的回答中提到的,您对日期字符串使用了错误的语法。 x用于一年中的一周(读here

    要解决手头的问题,你可以使用

    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSSSS").parseLocalDateTime(dateTimeString)