从String解析为Date会抛出Unparsable

从String解析为Date会抛出Unparsable

本文介绍了从String解析为Date会抛出Unparsable Date Error的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 data 的变量,它的今日日期为以下格式: Thu May 24 13:14:41 BRT 2018 。然后我将其格式化为MySQL的日期类型格式,即 yyyy-MM-dd 。此代码执行此操作:

I have an variable called data, and it has today's date as in this format: Thu May 24 13:14:41 BRT 2018. Then I format it to MySQL's Date type format, which is yyyy-MM-dd. This code does it:

String dataFormatada = new SimpleDateFormat("yyyy-MM-dd").format(data);

我想做的是将它带回日期类型。我尝试了一些事情,但他们没有工作。主要解决方案是按照其他中的说明进行操作,有了一点mod,我得到了我想要的东西:

What I want to do is to bring it back to Date type. I've tried somethings but they didn't work. The main solution is to do as discribed in this other Stack Overflow's questioin, and with a little mod I got to what's suposely what I want:

String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date result =  df.parse(target);
System.out.println(result);

但它不起作用,因为我在尝试解析时遇到此错误:

But it doesn't work as I get this error when trying to parse:

java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"

所以我不能重新格式化数据变量,我不能带 dataFormatada 返回日期格式。如何将 dataFormatada 带到格式为yyyy-MM-dd的日期类型?

So I cannot just reformat the data variable, and I cannot bring dataFormatada back to Date format. How do I bring dataFormatada to Date type formatted as yyyy-MM-dd?

推荐答案

您的目标字符串格式位于 EEE MMM dd HH:mm:ss zzz yyyy 格式。所以你需要使用 EEE MMM dd HH:mm:ss zzz yyyy 作为模式而不是 yyyy-MM-dd

Your target String format is in EEE MMM dd HH:mm:ss zzz yyyy format. So you need to use EEE MMM dd HH:mm:ss zzz yyyy as pattern instead of yyyy-MM-dd.

    String target = "Thu Sep 28 20:29:30 JST 2000";
    DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
    Date result =  df.parse(target);
    System.out.println(result);

如果你想转换Date对象,即结果为 yyyy-MM-dd 然后请使用以下代码。

And if you want convert Date object i.e result to yyyy-MM-dd then please use the below code.

    DateFormat dfDateToStr = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
    String formattedDate  = dfDateToStr.format(result);
    System.out.println("Formatted Date String : "+formattedDate);

这篇关于从String解析为Date会抛出Unparsable Date Error的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:12