首页 > 解决方案 > 使用simpleDateFormat java解析日期

问题描述

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

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

但 date1 是:Sat Dec 21 22:47:19 IRST 2019

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

标签: javadateparsingsimpledateformat

解决方案


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 及其格式化 APISimpleDateFormat已过时且容易出错。建议完全停止使用它们并切换到现代日期时间 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 工作level 仍然不符合 Java-8,请检查Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project


推荐阅读