Convert Date in Java [duplicate] - java

This question already has answers here:
How to convert getTime() to 'YYYY-MM-DD HH24:MI:SS' [duplicate]
(3 answers)
Java string to date conversion
(17 answers)
Closed 4 years ago.
I have a date like "Sun Apr 01 01:00:00 EEST 2018" and I want to convert it to the following numeric format: Day-Month-Year Hours:Minutes:Seconds
I want to do that in Java. Can anybody help?
Thank you a lot

I would use the DateTimeFormatter for this. You can find more information in the docs.
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
However, here an example:
DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
LocalDateTime date = LocalDateTime.parse("Sun Apr 01 01:00:00 EEST 2018", parser);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
System.out.println(formatter.format(date)); //01-04-2018 01:00:00
The Locale.US part is required even if you don't live in the US, otherwise it may not be able to parse Sun to Sunday and Apr to April an so on. Probably it works with Locale.UK to and more but for example it didn't work for me without because i live in switzerland.

Related

What is wrong with this java date formatter?

I'm trying to format the date you see as a String in the below code, to be able to have it as a LocalDateTime object, but I'm getting an exception, I'm following this guide https://mkyong.com/java8/java-8-how-to-convert-string-to-localdate/, but unfortunately it doesn't have and example like the date I have below, can someone please give me a hand here? I would really appreciate :)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE MMM d hh:mm:ss zzz yyyy", Locale.US);
String date = "Wed Nov 18 00:00:00 COT 2020";
LocalDateTime localDateTime = LocalDateTime.parse(date, formatter);
System.out.println(localDateTime);
System.out.println(formatter.format(localDateTime));
I am getting:
java.time.format.DateTimeParseException: Text 'Wed Nov 18 00:00:00 COT
2020' could not be parsed at index 0
If you want round trip parsing/formatting with Zones try
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
String date = "Wed Nov 18 00:00:00 COT 2020";
ZonedDateTime localDateTime = ZonedDateTime.parse(date, formatter);
System.out.println(localDateTime);
System.out.println(formatter.format(localDateTime));
To answer the question as asked in the title, What is wrong with this Java date formatter?
EEEE is for full name of the day of the week like Monday. For the abbreviation like Mon you need either E, EE or EEE.
As others have said, lower case hh is for clock hour within AM or PM from 01 through 12, so cannot parse your hour of 00. And even if it could, it would not provide enough information for the time of day. For hour of day from 00 though 23 you need upper case HH.
There’s a more basic problem that Basil Bourque already mentioned in a comment: The result of parsing a time zone abbreviation like COT is generally undefined. While COT may have only one definition, I don’t know, most of the most common abbreviations are ambiguous, and you don’t know what you get from parsing them.
As has also been mentioned your formatter cannot be used for formatting a LocalDateTime. A LocalDateTime hasn’t got any time zone. The formatter requires a time zone for the abbreviated time zone name, zzz. You may either format a ZonedDateTime, or you may modify the formatter to have an override zone using its withZone method.
A tip: When you don’t know why parsing fails, try formatting the expected value with the same formatter and compare the result to the string you are trying to parse. Most often the difference will lead you on the right track. Like this:
ZonedDateTime val = ZonedDateTime.of(
2020, 11, 18, 0, 0, 0, 0, ZoneId.of("America/Bogota"));
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("EEEE MMM d hh:mm:ss zzz yyyy", Locale.US);
String toBeParsed = "Wed Nov 18 00:00:00 COT 2020";
String formatted = val.format(formatter);
System.out.println("String to be parsed: " + toBeParsed);
System.out.println("Formatted string: " + formatted);
Output:
String to be parsed: Wed Nov 18 00:00:00 COT 2020
Formatted string: Wednesday Nov 18 12:00:00 COT 2020
The difference are Wednesday and 12, so it seems the bugs in the pattern are at EEEE and hh.
Your string seems to come out of the toString method of the outdated java.util.Date class. To parse the string from there see one of the answers linked to at the bottom. Or still better, get hold of the Date object, convert it to a modern Instant using its toInstant method and perform any further conversions from there. Or yet still better, stop using Date completely.
Links
How to parse the result from Date.toString():
Answer by Arvind Kumar Avinash
Answer by Arvind Kumar Avihash
Answer by Arvind Kumar Avinash
My answer
Answer by Basil Bourque
And of course the answer by Scary Wombat to this question

Simple date format parses 2k11 like values which should throw an exception [duplicate]

This question already has answers here:
SimpleDateFormat parse(string str) doesn't throw an exception when str = 2011/12/12aaaaaaaaa?
(7 answers)
Why java SimpleDateFormat can parse formatted text with extra characters?
(4 answers)
Closed 3 years ago.
I am trying to validate dates using simple data format and it parses strange dates.
val dateFormat = new SimpleDateFormat("dd MMM, yyyy")
dateFormat.setLenient(false)
dateFormat.parse("01 Jan, 2k11")
Sun Jan 01 00:00:00 IST 2
fast time : -62104253400000
cDate : C.E. 2-01-01T00:00:00.000+0530
I started digging through the source code for SimpleDateFormat, and read enough to glean what appears to be happening here. What is happening is that your year component 2k11 is being interpreted as a two digit year (actually one digit, 2), and everything that follows is being ignored as not being part of the date pattern. Consider the following code which produces the same result:
DateFormat dateFormat = new SimpleDateFormat("dd MMM, yyyy");
dateFormat.setLenient(false);
Date blah = dateFormat.parse("01 Jan, 2 Jon Skeet");
System.out.println(blah);
This prints:
Sun Jan 01 00:00:00 CET 2
As you can see, the intepreted year is 2, and the Jon Skeet blurb was ignored. To understand exactly why SimpleDateFormat is doing this, read the source code.

Month is always January at date parsing [duplicate]

This question already has answers here:
Java SimpleDateFormat always returning January for Month
(4 answers)
Closed 3 years ago.
i tried to convert a date String into a date object, but unfortunately the month is set every time to Jan and I can't figure out why.
String date = "20190522T072424.000Z";
DateFormat sdf = new SimpleDateFormat("yyyyMMDD'T'HHmmss.SSS'Z'");
System.out.println(sdf.parse(date));
Output: Tue Jan 22 07:24:24 CET 2019
As AxelH said, the format DD is for day of the year. If you use yyyyMMdd'T'HHmmss.SSS'Z' you will print Wed May 22 07:24:24 WEST 2019.
For reference: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Parsing date format with timezone [duplicate]

This question already has answers here:
Java SimpleDateFormat Pattern for JavaScript Date
(4 answers)
Closed 5 years ago.
I'm trying to parse a date string with a GMT+100
new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss").parse("Thu Apr 23 2015 11:30:49 GMT+0100")
Comes out as
Thu Apr 23 11:30:49 UTC 2015
If I add z or Z or X to the format, it's unparseable. If I don't add it, it's off by the offset, one hour.
What is the right way to parse this date?
--
Update: this differs from Java SimpleDateFormat Pattern for JavaScript Date in two ways: 1) this question is pure java and would have accepted answers other than those using SimpleDateFormat (i.e. new Java 8 features), and 2) the solution here is different to the other question.
Your expresssion should be EEE MMM dd yyyy HH:mm:ss 'GMT'Z(including the quotes), so your code is as follows:
new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z").parse("Thu Apr 23 2015 11:30:49 GMT+0100")
HOW THIS WORKS
According to the docs, anything passed in between single quotes(') in SimpleDateFormat pattern is not interpolated, but is assumed be just a part of the date format to be ignored while parsing.
And the equivalent of +0100 in SimpleDateFormat pattern terms is Z

Confused with Converting the date with SimpleDateFormat [duplicate]

This question already has answers here:
How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?
(5 answers)
Closed 5 years ago.
I have a problem with date converting. I use the following program and I expect the output: 19.05.2017
But the output is: 05.00.2017
Can anybody help?
String t = "Fri May 19 00:00:00 CEST 2017";
Date d = new SimpleDateFormat("EEE MMM DD hh:mm:ss zzzz YYYY", Locale.US).parse(t);
String s = new SimpleDateFormat("dd.mm.yyyy").format(d).toString();
System.out.println(s);
A surprising result. The oldfashioned classes SimpleDateFormat and friends are full of surprises. This is meant as a negative thing.
Uppercase DD is day of year. Lowercase hh is hour of AM or PM (1 through 12). Uppercase YYYY is weekbased year (only useful with week number). So you are asking for a date that is a Friday in May and the 19th day of the year. Obviously this is not possible.
The result of parsing is Thu Jan 05 23:00:00 CET 2017. Apparently SimpleDateFormat opts for giving you a Friday and for using the zone offset of 2 hours implied by CEST even though the date it has chosen is not at the time of year where CEST (summer time) is in use. I don’t know whether it just gives you the first Friday of the weekbased year (Friday in week 1 of the year). Friday at 0000 hours at offset GMT+2 equals Thursday at 23 at GMT+1, which is CET.
Next for the formatting, 05 is the date as expected, but lowercase mm means minutes. Since the minutes are 0, you get 00. You got the right year.
Rather than using the outdated classes that give you such surprises, I agree with Sam’s answer that you should use the newer classes in java.time:
ZonedDateTime dt = ZonedDateTime.parse(t,
DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US));
String s = dt.format(DateTimeFormatter.ofPattern("dd.MM.uuuu"));
This code gives you 19.05.2017 as you had expected. One of the good things about the modern classes is, if you try to parse with your original format pattern string, you will get a DateTimeParseException so you will know something is wrong. I certainly prefer an exception over incorrect output.
Another good thing is these classes respect the time zone in the input and use it in the output too (unless you explicitly instruct them otherwise). They will never turn Friday 6 January into Thursday 5 January because of some funny time zone issue.
Your input date is in Central European Summer Time and your date format is a bit wrong. Try
SimpleDateFormat input = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzzz yyyy");
You might want to set the timezone on the output date format in order to get the date in the correct local time.
Ideally you'd move over to use a java.time style as shown here:
https://www.mkyong.com/java/java-convert-date-and-time-between-timezone/

Categories

Resources