将字符串转换为 java.util.Date

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2735023/
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-13 12:16:21  来源:igfitidea点击:

Convert String to java.util.Date

javadatedatetime-format

提问by Vinayak Bevinakatti

I am storing the dates in a SQLite database in this format:

我以这种格式将日期存储在 SQLite 数据库中:

d-MMM-yyyy,HH:mm:ss aaa

When I retrieve the date with that format I am get every thing fine except the hour. The hour is always 00. Here is my output:

当我使用该格式检索日期时,除了小时之外,其他一切都很好。小时总是00。这是我的输出:

String date--->29-Apr-2010,13:00:14 PM
After convrting Date--->1272479414000--Thu Apr 29 00:00:14 GMT+05:30 2010

Here is the code:

这是代码:

    Date lScheduledDate = CalendarObj.getTime();
    DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
    SomeClassObj.setTime(formatter.format(lScheduledDate));

    String lNextDate = SomeClassObj.getTime();
    DateFormat lFormatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
    Date lNextDate = (Date)lFormatter.parse(lNextDate);
    System.out.println("output here"+lNextDate);

What am I doing wrong?

我究竟做错了什么?

采纳答案by Thomas L?tzer

I think your date format does not make sense. There is no 13:00 PM. Remove the "aaa" at the end of your format or turn the HH into hh.

我认为您的日期格式没有意义。没有 13:00 PM。删除格式末尾的“aaa”或将 HH 变成 hh。

Nevertheless, this works fine for me:

尽管如此,这对我来说很好用:

String testDate = "29-Apr-2010,13:00:14 PM";
DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
Date date = formatter.parse(testDate);
System.out.println(date);

It prints "Thu Apr 29 13:00:14 CEST 2010".

它打印“Thu Apr 29 13:00:14 CEST 2010”。

回答by Guillaume

You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).

您应该在 DateFormat 中设置一个 TimeZone,否则它将使用默认值(取决于计算机的设置)。

回答by azp74

It sounds like you may want to use something like SimpleDateFormat. http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html

听起来您可能想要使用 SimpleDateFormat 之类的东西。 http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html

You declare your date format and then call the parse method with your string.

您声明您的日期格式,然后使用您的字符串调用 parse 方法。

private static final DateFormat DF = new SimpleDateFormat(...);
Date myDate = DF.parse("1234");

And as Guillaume says, set the timezone!

正如纪尧姆所说,设置时区!

回答by Ole V.V.

java.time

时间

While in 2010, java.util.Datewas the class we all used (toghether with DateFormatand Calendar), those classes were always poorly designed and are now long outdated. Today one would use java.time, the modern Java date and time API.

虽然在 2010 年java.util.Date是我们都使用的类(连同DateFormatCalendar),但这些类的设计总是很糟糕,现在已经过时了。今天人们会使用 java.time,现代 Java 日期和时间 API。

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy,HH:mm:ss");

        String dateTimeStringFromSqlite = "29-Apr-2010,13:00:14";
        LocalDateTime dateTime = LocalDateTime.parse(dateTimeStringFromSqlite, formatter);
        System.out.println("output here: " + dateTime);

Output is:

输出是:

output here: 2010-04-29T13:00:14

此处输出:2010-04-29T13:00:14

What went wrong in your code?

你的代码出了什么问题?

The combination of uppercase HHand aaain your format pattern strings does not make much sense since HHis for hour of day, rendering the AM/PM marker from aaasuperfluous. It should not do any harm, though, and I have been unable to reproduce the exact results you reported. In any case, your comment is to the point no matter if one uses the old-fashioned SimpleDateFormator the modern DateTimeFormatter:

大写HHaaa格式模式字符串的组合没有多大意义,因为HH是一天中的一个小时,使 AM/PM 标记变得aaa多余。不过,它应该不会造成任何伤害,而且我无法重现您报告的确切结果。无论如何,无论您使用的是老式SimpleDateFormat还是现代,您的评论都是中肯的DateTimeFormatter

'aaa' should not be used, if you use 'aaa' then specify 'hh'

不应使用“aaa”,如果使用“aaa”,则指定“hh”

Lowercase hhis for hour within AM or PM, from 01 through 12, so would require an AM/PM marker.

小写hh表示 AM 或 PM 中的小时,从 01 到 12,因此需要 AM/PM 标记。

Other tips

其他提示

  • In your database, since I understand that SQLite hasn't got a built-in datetime type, use the standard ISO 8601 format and store time in UTC, for example 2010-04-29T07:30:14Z(the modern Instantclass parses and formats such strings as its default, that is, without any explicit formatter).
  • Don't use an offset such as GMT+05:30for time zone. Prefer a real time zone, for example Asia/Colombo, Asia/Kolkata or America/New_York.
  • If you wanted to use the outdated DateFormat, its parsemethod returns a Date, so you don't need the cast in Date lNextDate = (Date)lFormatter.parse(lNextDate);.
  • 在您的数据库中,由于我知道 SQLite 没有内置日期时间类型,例如,使用标准 ISO 8601 格式并以 UTC 存储时间2010-04-29T07:30:14Z(现代Instant类解析和格式化此类字符串作为其默认值,即,没有任何明确的格式化程序)。
  • 不要使用偏移量,例如GMT+05:30时区。首选实时时区,例如亚洲/科伦坡、亚洲/加尔各答或美洲/纽约。
  • 如果你想使用过时的DateFormat,它的parse方法返回一个Date,所以你不需要在Date lNextDate = (Date)lFormatter.parse(lNextDate);.

Question: Can I use java.time on Android?

问题:我可以在 Android 上使用 java.time 吗?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

是的,java.time 在较旧和较新的 Android 设备上都能很好地工作。它只需要至少Java 6

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It's called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bpwith subpackages.
  • 在 Java 8 及更高版本和更新的 Android 设备(从 API 级别 26)中,现代 API 是内置的。
  • 在 Java 6 和 7 中获得 ThreeTen Backport,现代类的 backport(ThreeTen for JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保从org.threeten.bp子包中导入日期和时间类。

Links

链接