Java 如何解析日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/999172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:05:07  来源:igfitidea点击:

How to parse a date?

javadatesimpledateformat

提问by fenec

I am trying to parse this date with SimpleDateFormatand it is not working:

我正在尝试解析此日期,SimpleDateFormat但它不起作用:

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

public class Formaterclass {
    public static void main(String[] args) throws ParseException{
        String strDate = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date dateStr = formatter.parse(strDate);
        String formattedDate = formatter.format(dateStr);
        System.out.println("yyyy-MM-dd date is ==>"+formattedDate);
        Date date1 = formatter.parse(formattedDate);

        formatter = new SimpleDateFormat("dd-MMM-yyyy");
        formattedDate = formatter.format(date1);
        System.out.println("dd-MMM-yyyy date is ==>"+formattedDate);
    }
}

If I try this code with strDate="2008-10-14", I have a positive answer. What's the problem? How can I parse this format?

如果我使用 strDate= 尝试此代码"2008-10-14",我会得到肯定的答案。有什么问题?我该如何解析这种格式?

PS. I got this date from a jDatePickerand there is no instruction on how modify the date format I get when the user chooses a date.

附注。我从 a 获得了这个日期,jDatePicker并且没有关于如何修改用户选择日期时获得的日期格式的说明。

采纳答案by jwl

You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.

您不能期望使用设置为不同格式的 SimpleDateFormat 来解析日期。

To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):

要解析您的“Thu Jun 18 20:56:02 EDT 2009”日期字符串,您需要一个像这样的 SimpleDateFormat(大致):

SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");

Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.

使用它来将字符串解析为日期,然后使用其他 SimpleDateFormat 将该日期转换为您想要的格式。

        String input = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
        Date date = parser.parse(input);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(date);

        ...

JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

JavaDoc:http: //docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

回答by Eddie

The problem is that you have a date formatted like this:

问题是您的日期格式如下:

Thu Jun 18 20:56:02 EDT 2009

But are using a SimpleDateFormatthat is:

但是正在使用的SimpleDateFormat是:

yyyy-MM-dd

The two formats don't agree. You need to construct a SimpleDateFormatthat matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormatlike this:

两种格式不一致。您需要构造一个SimpleDateFormat与您尝试解析为日期的字符串的布局相匹配的。将事物排列起来以使其易于查看,您需要SimpleDateFormat这样的:

EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009

Check the JavaDoc page I linked to and see how the characters are used.

检查我链接到的 JavaDoc 页面,看看这些字符是如何使用的。

回答by Yishai

How about getSelectedDate? Anyway, specifically on your code question, the problem is with this line:

getSelectedDate怎么样?无论如何,特别是在您的代码问题上,问题出在这一行:

new SimpleDateFormat("yyyy-MM-dd");

The string that goes in the constructor has to match the format of the date. The documentation for how to do that is here. Looks like you need something close to "EEE MMM d HH:mm:ss zzz yyyy"

构造函数中的字符串必须与日期格式相匹配。有关如何执行此操作的文档在此处。看起来你需要一些接近“EEE MMM d HH:mm:ss zzz yyyy”的东西

回答by Basil Bourque

We now have a more modern way to do this work.

我们现在有一种更现代的方式来完成这项工作。

java.time

时间

The java.timeframework is bundled with Java 8 and later. See Tutorial. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extraproject. They are a vast improvement over the troublesome old classes, java.util.Date/.Calendar et al.

java.time框架捆绑在一起的Java 8及更高版本。请参阅教程。这些新类的灵感来自Joda-Time,由JSR 310定义,并由ThreeTen-Extra项目扩展。它们是对麻烦的旧类 java.util.Date/.Calendar 等的巨大改进。

Note that the 3-4 letter codes like EDTare neither standardized nor unique. Avoid them whenever possible. Learn to use ISO 8601standard formats instead. The java.time framework may take a stab at translating, but many of the commonly used codes have duplicate values.

请注意,像这样的 3-4 个字母代码EDT既不是标准化的也不是唯一的。尽可能避免它们。学习改用ISO 8601标准格式。java.time 框架可能会尝试翻译,但许多常用代码都有重复值。

By the way, note how java.time by default generates strings using the ISO 8601 formats but extended by appending the name of the time zone in brackets.

顺便说一下,请注意 java.time 默认如何使用 ISO 8601 格式生成字符串,但通过在括号中附加时区名称进行扩展。

String input = "Thu Jun 18 20:56:02 EDT 2009";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM d HH:mm:ss zzz yyyy" , Locale.ENGLISH );
ZonedDateTime zdt = formatter.parse ( input , ZonedDateTime :: from );

Dump to console.

转储到控制台。

System.out.println ( "zdt : " + zdt );

When run.

跑的时候。

zdt : 2009-06-18T20:56:02-04:00[America/New_York]

zdt : 2009-06-18T20:56:02-04:00[美国/纽约]

Adjust Time Zone

调整时区

For fun let's adjust to the India time zone.

为了好玩,让我们适应印度时区。

ZonedDateTime zdtKolkata = zdt.withZoneSameInstant ( ZoneId.of ( "Asia/Kolkata" ) );

zdtKolkata : 2009-06-19T06:26:02+05:30[Asia/Kolkata]

zdtKolkata : 2009-06-19T06:26:02+05:30[亚洲/加尔各答]

Convert to j.u.Date

转换为 juDate

If you really need a java.util.Date object for use with classes not yet updated to the java.time types, convert. Note that you are losing the assigned time zone, but have the same moment automatically adjusted to UTC.

如果您确实需要一个 java.util.Date 对象与尚未更新为 java.time 类型的类一起使用,请转换。请注意,您正在丢失指定的时区,但同一时刻会自动调整为UTC

java.util.Date date = java.util.Date.from( zdt.toInstant() );

回答by Edgar Civil

In response to: "How to convert Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México)) to dd-MM-yy in Java?", it was marked how duplicate

回应:“ How to convert Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México)) to dd-MM-yy in Java?”,它被标记为如何重复

Try this: With java.util.Date, java.text.SimpleDateFormat, it's a simple solution.

试试这个:使用java.util.Date, java.text.SimpleDateFormat,这是一个简单的解决方案。

public static void main(String[] args) throws ParseException {

    String fecha = "Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México))";
    Date f = new Date(fecha);

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    sdf.setTimeZone(TimeZone.getTimeZone("-5GMT"));
    fecha = sdf.format(f);
    System.out.println(fecha);
}