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

如何转换UTC日期字符串并删除Java中的T和Z?

  •  3
  • PacificNW_Lover  · 技术社区  · 6 年前

    AM使用Java 1.7。

    正在尝试转换:

    2018-05-23T23:18:31.000Z 
    

    进入之内

    2018-05-23 23:18:31
    

    dateutils类:

    public class DateUtils {
    
        public static String convertToNewFormat(String dateStr) throws ParseException {
            TimeZone utc = TimeZone.getTimeZone("UTC");
            SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
            sdf.setTimeZone(utc);
            Date convertedDate = sdf.parse(dateStr);
            return convertedDate.toString();
        }
    }
    

    尝试使用时:

    String convertedDate = DateUtils.convertToNewFormat("2018-05-23T23:18:31.000Z");
    System.out.println(convertedDate);
    

    获取以下异常:

    Exception in thread "main" java.text.ParseException: Unparseable date: "2018-05-23T23:22:16.000Z"
       at java.text.DateFormat.parse(DateFormat.java:366)
       at com.myapp.utils.DateUtils.convertToNewFormat(DateUtils.java:7)
    

    我可能做错什么了?

    有没有一种更简单的方法是(例如,ApacheCommonsLib)?

    4 回复  |  直到 6 年前
        1
  •  5
  •   jkumaranc    6 年前

    试试这个。您必须使用一种模式进行解析,另一种模式用于格式化。

    public static String convertToNewFormat(String dateStr) throws ParseException {
        TimeZone utc = TimeZone.getTimeZone("UTC");
        SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sourceFormat.setTimeZone(utc);
        Date convertedDate = sourceFormat.parse(dateStr);
        return destFormat.format(convertedDate);
    }
    
        2
  •  6
  •   Basil Bourque    6 年前

    DR

    Instant.parse( "2018-05-23T23:18:31.000Z" )                // Parse this String in standard ISO 8601 format as a `Instant`, a point on the timeline in UTC. The `Z` means UTC.
    .atOffset( ZoneOffset.UTC )                                // Change from `Instant` to the more flexible `OffsetDateTime`.
    .format(                                                   // Generate a String representing the value of this `OffsetDateTime` object.
        DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" )   // Specify a formatting pattern as desired.
    )                                                          // Returns a `String` object.
    

    2018年5月23日23:18:31

    ISO 8601标准

    您的输入字符串是标准的 ISO 8601 格式。

    这个 java.time时间 类在解析/生成字符串时默认使用这些标准格式。

    这个 T 将年-月-日部分与小时-分钟-秒分开。这个 Z 发音 Zulu 意味着 UTC .

    java.time时间

    您使用的是多年前被 java.time时间 课程。阿帕奇 DateUtils 也不再需要,因为您将在 java.time时间 也。

    将该输入字符串作为 Instant 对象。这个 Instant 类表示时间线上的某一时刻 UTC 决议为 nanoseconds (小数点后最多九(9)位)。

    String input = "2018-05-23T23:18:31.000Z" ;
    Instant instant = Instant.parse( input ) ;
    

    要以另一种格式生成字符串,我们需要一个更灵活的对象。这个 即时 类是一个基本的构建块。让 s convert it to a offsetdatetime`,使用UTC本身作为从UTC的指定偏移量。

    OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ; 
    

    定义与所需输出匹配的格式模式。

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
    String output = odt.format( f ) ;
    

    提示:考虑使用 DateTimeFormatter::ofLocalized… 方法根据 Locale 而不是硬编码格式化模式。


    关于 java.time时间

    这个 java.time 框架是在Java 8和之后构建的。这些阶级取代了麻烦的旧阶级。 legacy 日期时间类,如 java.util.Date , Calendar ,& SimpleDateFormat .

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

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

    你可以换 java.time时间 直接使用数据库的对象。使用A JDBC driver 符合 JDBC 4.2 或者以后。不需要字符串,不需要 java.sql.* 课程。

    在哪里获取java.time类?

    这个 ThreeTen-Extra Project使用其他类扩展java.time。这个项目是将来可能添加到java.time的一个试验场。您可以在这里找到一些有用的类,例如 Interval , YearWeek , YearQuarter more .

        3
  •  3
  •   Rami.Q    6 年前

    对于没有Java 1.7的其他限制:

    自Java 1.8以来,您可以使用它 LocalDateTime ZonedDateTime 从包中 java.time

    public static void main(String[] args) {
        String sourceDateTime           = "2018-05-23T23:18:31.000Z";
        DateTimeFormatter sourceFormat  = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        DateTimeFormatter targetFormat  = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
        LocalDateTime dateTime          = LocalDateTime.parse(sourceDateTime, sourceFormat);
        String formatedDateTime         = dateTime.atZone(ZoneId.of("UTC")).format(targetFormat);
        System.out.println(formatedDateTime);
    }
    

    编辑:(见注释)

    从Oracle Java文档中引用 LocalDateTime :

    localdatetime是一个不可变的日期时间对象,它表示 日期时间,通常视为年-月-日-小时-分-秒。其他 日期和时间字段,例如年中的某一天、周中的某一天和 一年中的某一周,也可以访问。时间表示为纳秒。 精准度。例如,值“2007年10月2日 13:45.30.123456789“可以存储在本地日期时间中。

    此类不存储或表示时区。相反,它是一个 用于生日的日期说明,与 墙上的时钟上显示的当地时间。它不能代表一个瞬间 没有附加信息的时间线,如偏移量或 时区。

    操作要求将输入字符串解析为日期时间(如年-月-日-时-分-秒),文档中说

    本地日期时间…表示日期时间,通常视为 年-月-日-时-分-秒

    所以这里没有重要的信息丢失。那部分呢 dateTime.atZone(ZoneId.of("UTC")) 返回 分区日期时间 因此,如果用户需要使用时区…等,那么在此时再次处理zimezone。

    因此,不要试图强迫用户使用您在答案中提供的“唯一”解决方案。

        4
  •  0
  •   Mạnh Quyết Nguyễn    6 年前

    YYYY 与年份部分不匹配。在Java 7中,您需要 yyyy .

    为了 T 使用 'T' 与之匹配

    你也失去了米尔斯康德的势力: .SSS

    试试这个:

    String dateStr="2018-05-23T23:18:31.000Z";
    TimeZone utc = TimeZone.getTimeZone("UTC");
    SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(utc);
    Date convertedDate = sdf.parse(dateStr);
    convertedDate.toString();
    
    推荐文章