Sunday 31 December 2017

java - Parsing from String to Date throws Unparsable Date Error

itemprop="text">

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);


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 href="https://stackoverflow.com/questions/4496359/how-to-parse-date-string-to-date">
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"


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?


itemprop="text">
class="normal">Answer



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);


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);


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...