简体   繁体   English

android:如何将字符串转换为日期

[英]android: how to convert a string to Date

I am making an app that use an API that give data with timestamps.我正在制作一个使用提供时间戳数据的 API 的应用程序。 The timestamp looks like:时间戳看起来像:

Jul 20, 2018

I want to convert the string to a date.我想将字符串转换为日期。 I try this code to parse the string to a Date.我尝试使用此代码将字符串解析为日期。

DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.US);
            Date date = dateFormat.parse("Jul 20, 2018");

but I even can't compile my code.但我什至无法编译我的代码。 Every time I try to parse a string with dateformat.parse() I got the following compile error:每次我尝试使用 dateformat.parse() 解析字符串时,都会出现以下编译错误:

java.text.ParseException

This even shows up when hovering above the the .parse() in code I browsed the whole day and tried a couple of different thing, but every time I use .parse() I got this error.这甚至出现在我浏览了一整天并尝试了几种不同的代码的 .parse() 上方时,但每次我使用 .parse() 时都会出现此错误。 I really dot know what to do any more.我真的不知道该做什么了。

I don't have the permission to post images yet, but you can watch the screenshot over here: https://imgur.com/ux5l9hY我还没有发布图片的权限,但你可以在这里观看截图: https ://imgur.com/ux5l9hY

I am using Java 8 (with support for lambda notation).我正在使用 Java 8(支持 lambda 表示法)。 I am using androidx.legacy:legacy-support library, minimum API 19 and targetting API 28. (So the solution for this problem should support older devices as well)我正在使用 androidx.legacy:legacy-support 库,最低 API 19 和目标 API 28。(所以这个问题的解决方案也应该支持旧设备)

Other things I tried but failed:我尝试过但失败的其他事情:

Android, How can I Convert String to Date? Android,如何将字符串转换为日期?

Cant convert String to date in android 无法在android中将字符串转换为日期

How to convert "2017-04-26T20:55:00.000Z" string to a Date in java android studio 如何在java android studio中将“2017-04-26T20:55:00.000Z”字符串转换为日期

Android date format parse throwing an Unhandled Exception Android 日期格式解析抛出未处理的异常

How to convert a date in this format (Tue Jul 13 00:00:00 CEST 2010) to a Java Date (The string comes from an alfresco property) 如何将此格式的日期(Tue Jul 13 00:00:00 CEST 2010)转换为 Java 日期(字符串来自 alfresco 属性)

Convert string to Date in java 在java中将字符串转换为日期

That error is telling you that the function you are calling can throw a specific exception and you are not catching it ( dateFormat.parse(...) can throw a ParseException error if the string cannot be parsed).该错误告诉您,您正在调用的函数可能会引发特定异常并且您没有捕获它(如果无法解析字符串, dateFormat.parse(...)可能会引发ParseException错误)。

Try something like this尝试这样的事情

try {
    DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.US);
    Date date = dateFormat.parse("Jul 20, 2018");
}
catch(ParseException pe ) {
    // handle the failure
}

java.time java.time

    DateTimeFormatter dateFormatter = DateTimeFormatter
            .ofLocalizedDate(FormatStyle.MEDIUM)
            .withLocale(Locale.US);
    LocalDate date = LocalDate.parse("Jul 20, 2018", dateFormatter); 

If you know that your date string is correct, just use the above code without any try - catch .如果您知道您的日期字符串是正确的,只需使用上面的代码而不使用任何try - catch If you need to validate the string (typically if it's input from a user or from a different system), do use try - catch , either directly around the parsing or in the place in your code where it's most convenient to handle any incorrect string.如果您需要验证字符串(通常是来自用户或来自不同系统的输入),请使用try - catch ,直接在解析周围或在代码中最方便处理任何不正确字符串的位置。 Example:例子:

    try {
        LocalDate date = LocalDate.parse("Jul 20, 2018", dateFormatter);
    } catch (DateTimeParseException dtpe) {
        dtpe.printStackTrace();
    } 

I am using java.time , the modern Java date and time API, because it's much nicer to work with, and the old SimpleDateFormat class in particular was renowned for being troublesome.我正在使用java.time ,这是现代 Java 日期和时间 API,因为它更易于使用,而且旧的SimpleDateFormat类尤其以麻烦而闻名。 One difference is: The old class threw a checked exception from parsing, which forced us to use either try - catch or a throws declaration on the surrounding method.一个区别是:旧类从解析中抛出了一个检查异常,这迫使我们在周围的方法上使用try - catchthrows声明。 The modern classes throw unchecked exceptions, which leaves it to us whether we want to catch and handle them or not.现代类会抛出未经检查的异常,这让我们决定是否要捕获和处理它们。 Don't be fooled though: they are still exceptions and may cause your app to crash, so better handle them if there is any possibility that a string that is not in the correct format occurs.不过不要上当:它们仍然是异常,可能会导致您的应用程序崩溃,因此如果有可能出现格式不正确的字符串,请更好地处理它们。

As a side note rather use Java's built-in date format than specifying your own.作为旁注,与其指定您自己的,不如使用 Java 的内置日期格式。 It's simpler and less error-prone and easier to adapt to audiences of other languages and cultures.它更简单,更不容易出错,更容易适应其他语言和文化的受众。 Your format coincides with the medium style format for the US locale, so I used this.您的格式与美国语言环境的中等样式格式一致,所以我使用了这个。

Question: Can I use java.time on Android?问题:我可以在 Android 上使用 java.time 吗?

Yes, java.time works nicely on older and newer Android devices.是的, java.time在较旧和较新的 Android 设备上运行良好。 It just requires at least Java 6 .它只需要至少 Java 6

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

Links链接

you can use to new API of Java 8 .您可以使用 Java 8 的新 API。

LocalDate date = LocalDate.parse(CharSequence text);

text - the text to parse such as "2007-12-03T10:15:30", not null. text - 要解析的文本,例如“2007-12-03T10:15:30”,不为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM