Java Android 使用 SimpleDateFormat 将字符串解析为日期时间

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

Android parsing String to Date time with SimpleDateFormat

javaandroiddatetime

提问by user2953680

I have the String 11/08/2013 08:48:10

我有字符串 11/08/2013 08:48:10

and i use SimpleDateFormat("MM/dd/yyyy HH:mm:ss")

我用 SimpleDateFormat("MM/dd/yyyy HH:mm:ss")

and when im parsing it throws an exception : unparseable date

当我解析它时抛出异常:无法解析的日期

what's wrong with it ?

它出什么问题了 ?

            String result = han.ExecuteUrl("http://"+han.IP+":8015/api/Values/GetLastChange"); 
            Log.d("Dal","result date time "+result); #result is 11/08/2013 08:48:10
            SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

            Date convertedDate = new Date();
            try
            {

                convertedDate = dateFormat.parse(result);
            }
            catch (ParseException e)
            {
                e.printStackTrace();
            }

回答by kalyan pvs

Its working try parse your date like this..

它的工作尝试像这样解析你的日期..

String dtStart = "11/08/2013 08:48:10";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
    date = format.parse(dtStart);
    System.out.println("Date ->" + date);
} catch (ParseException e) {
    e.printStackTrace();
}

回答by Harsh Patel

Working code is here.

工作代码在这里。

You can use below code to convert from String to Date

您可以使用以下代码将字符串转换为日期

String myStrDate = "11/08/2013 08:48:10";
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    try {
        Date date = format.parse(myStrDate);
        System.out.println(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

For reverse, it means, to convert from Date to String

对于反向,这意味着从日期转换为字符串

SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    try {
        Date date = new Date();
        String datetime = myFormat.format(date);
        System.out.println("Current Date Time in give format: " + datetime);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

For more reference, regarding Date and Time formatting. Visit developer site

有关日期和时间格式的更多参考。访问开发者网站

回答by Ole V.V.

java.time and ThreeTenABP

java.time 和 ThreeTenABP

It's not the answer that you asked for, but it should be the answer that other readers want in 2020 and onward.

这不是您要求的答案,而是其他读者在 2020 年及以后想要的答案。

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss");
    String result = "11/08/2013 08:48:10"; 
    LocalDateTime dateTime = LocalDateTime.parse(result, formatter);
    System.out.println("Parsed date and time: " + dateTime);

Output from this snippet is:

这个片段的输出是:

Parsed date and time: 2013-11-08T08:48:10

解析日期和时间:2013-11-08T08:48:10

The Dateclass that you used is poorly designed and long outdated, so don't use that anymore. Instead I am using java.time, the modern Java date and time API. If you need a Datefor a legacy API that you cannot afford to upgrade just now, the conversion is:

Date您使用的类设计不佳且已过时,因此请不要再使用它。相反,我使用的是 java.time,现代 Java 日期和时间 API。如果你需要一个Date你现在无法升级的遗留 API,转换是:

    Instant i = dateTime.atZone(ZoneId.systemDefault()).toInstant();
    Date oldfashionedDate = DateTimeUtils.toDate(i);

    System.out.println("Converted to old-fashioned Date: " + oldfashionedDate);

Converted to old-fashioned Date: Fri Nov 08 08:48:10 CET 2013

转换为老式日期:Fri Nov 08 08:48:10 CET 2013

What went wrong in your code?

你的代码出了什么问题?

what's wrong with it ?

它出什么问题了 ?

The only thing wrong with your code is you're using the notoriously troublesome SimpleDateFOrmatand the poorly designed Dateclass. Which wasn't wrong when you asked the question in 2013. java.time didn't come out until 4 months later.

您的代码唯一的错误是您使用了臭名昭著的麻烦SimpleDateFOrmat且设计糟糕的Date类。你在 2013 年问这个问题的时候没有错。java.time 直到 4 个月后才出来。

Your code is running fine. One may speculate that a leading space or the like in your string has prevented parsing. If this was the problem, try parsing result.trim()rather than just resultsince trim()returns a string with the leading and trailing whitespace removed.

您的代码运行良好。人们可能会推测字符串中的前导空格等阻止了解析。如果这是问题所在,请尝试解析result.trim()而不是仅仅result因为trim()返回删除了前导和尾随空格的字符串。

Question: Doesn't java.time require Android API level 26?

问题:java.time 不需要 Android API 级别 26 吗?

java.time works nicely on both 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. Only in this case the conversion to Dateis a little simpler: Date.from(i).
  • In non-Android 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 是内置的。只有在这种情况下,转换为Date更简单一点:Date.from(i).
  • 在非 Android Java 6 和 7 中获得 ThreeTen Backport,现代类的 backport(ThreeTen for JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保从org.threeten.bp子包中导入日期和时间类。

Links

链接