【问题标题】:parsing date using simpleDateFormat java [duplicate]使用simpleDateFormat java解析日期[重复]
【发布时间】:2021-06-22 23:48:15
【问题描述】:

我想将字符串解析为日期,但获得的日期不正确。我的代码是这样的:

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S a");
date1 = df.parse("17-DEC-19 05.40.39.364000000 PM");

但 date1 是:2019 年 12 月 21 日星期六 22:47:19 IRST

我需要约会:* 2019 年 12 月 17 日 17:40:39 IRST

【问题讨论】:

  • 这里有溢出,即您添加的那些 milli 秒被解释为 364000 秒或 4 天 5 小时 6 分 40 秒。这些被添加到解析的日期。尝试添加df.setLenient(false),你应该得到一个错误。
  • 我建议你不要使用SimpleDateFormatDate。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APILocalDateTimeDateTimeFormatter

标签: java date parsing simpledateformat


【解决方案1】:

SimpleDateFormat 的精度不超过毫秒 (.SSS)。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSS a", Locale.ENGLISH);
        Date date1 = df.parse("17-DEC-19 05.40.39.364 PM");
        System.out.println(date1);
    }
}

输出:

Tue Dec 17 17:40:39 GMT 2019

请注意,java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern date-time API*

使用现代日期时间 API:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;

public class Main {
    public static void main(String[] args)  {
        DateTimeFormatter df = new DateTimeFormatterBuilder()
                .parseCaseInsensitive() // For case-insensitive (e.g. AM/am) parsing
                .appendPattern("dd-MMM-yy hh.mm.ss.n a")
                .toFormatter(Locale.ENGLISH);
        
        LocalDateTime ldt = LocalDateTime.parse("17-DEC-19 05.40.39.364000000 PM", df);
        System.out.println(ldt);
    }
}

输出:

2019-12-17T17:40:39.364

Trail: Date Time 了解有关现代日期时间 API 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多