convert Date to RFC Date time - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 hours ago.
Improve this question
I have a date field in the input as below
oldDate = 12-FEB-23
I want to convert this to
newDate = Sun Feb 13 05:30:00 IST 2023
using java 8 . Please help
Both oldDate and newDate are of Date type.
We dont want to use the java.util.Date class.
String oldDate = "13-FEB-23"
DateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
Date newDate = formatter.parse(oldDate);
With this, we are getting Sun Feb 13 00:00:00 IST 2023. So, we are setting hours to this as newDate.setHours(5), but this is deprecated. So, we don’t want to use it anymore.

Apparently you want to:
Parse a string representing a date.
Determine the first moment of the day an that date as seen in a particular time zone.
First, parsing.
The trick here is that all caps for a month abbreviation does not fit the cultural norms of any locale I know of. So we must build a custom formatter that ignores case.
DateTimeFormatter f =
new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern( "dd-MMM-uu" )
.toFormatter( Locale.US );
Do the parsing, to produce a LocalDate object representing the date alone.
String input = "12-FEB-23";
LocalDate localDate = LocalDate.parse( input , f );
Specify your desired time zone. IST is not a real time zone, so I do not know what you meant exactly. I suppose from your example offset of five and half hours ahead of UTC that you meant Asia/Kolkata rather than Europe/Dublin.
ZoneId z = ZoneId.of( "Asia/Kolkata" );
Determine the first moment of the day on that date in that zone. Never assume the day starts at 00:00. Some dates in same zones may start at another time such as 01:00. Let java.time determine the start.
ZonedDateTime zdt = localDate.atStartOfDay( z );
Sun Feb 13 05:30:00 IST 2023
If you mean to generate text in that format, define a formatter to suit your taste. Use the DateTimeFormatter class. Search Stack Overflow to learn more as this has been covered many many times already.
RFC Date time
If you meant a Request For Comments, you will need to specify which one.
If you meant RFC 1123, your example is incorrect, wisssing the comma after the day of the week.
String output = zdt.format( DateTimeFormatter.RFC_1123_DATE_TIME ) ;
See code run at Ideone.com.
Sun, 12 Feb 2023 00:00:00 +0530

Related

DateTimeFormatter fails to parse a date in JDK 17 where as passes in JDK8 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
The community reviewed whether to reopen this question 4 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Here is the code snippet
String date = "Wed, 20 Feb 2019 07:14:06 +0100";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss Z");
System.out.println(ZonedDateTime.parse(date, formatter).toString());
This code works fine with JDK8 where as fails in JDK17 with the following exception
Text 'Wed, 20 Feb 2019 07:14:06 +0100' could not be parsed at index 0
java.time.format.DateTimeParseException: Text 'Wed, 20 Feb 2019 07:14:06 +0100' could not be parsed at index 0
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2052)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1954)
at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:600)
tl;dr
OffsetDateTime
.parse(
"Wed, 20 Feb 2019 07:14:06 +0100" ,
DateTimeFormatter.RFC_1123_DATE_TIME
)
.toString()
2019-02-20T07:14:06+01:00
Details
Your problem has nothing to do with Java 8 versus Java 17.
Tip: Before blaming software that is formally specified, is thoroughly tested by enormous test suites, and is used by millions of programmers daily, suspect your own code first.
Locale
Specify a Locale. The locale determines the human language and cultural norms used in translating month names, etc.
If you do not specify a Locale, the JVM’s current default is applied implicitly. I would bet that when you ran your app at different times or on different machines, the JVM’s current default Locale varied.
Locale locale = Locale.US ;
DateTimeFormatter formatter =
DateTimeFormatter
.ofPattern( "EEE, d MMM yyyy HH:mm:ss Z" )
.withLocale( locale );
String input = "Wed, 20 Feb 2019 07:14:06 +0100" ;
ZonedDateTime zdt = ZonedDateTime.parse( input , formatter ) ;
String output = zdt.toString() ;
System.out.println( output );
See this code run at Ideone.com.
2019-02-20T07:14:06+01:00
RFC 1123
As commented by Ole V.V., your format happens to comply with the legacy standards RFC 1123, RFC 822, and RFC 2822.
The DateTimeFormatter class carries a pre-defined formatter object for that format. See the constant DateTimeFormatter.RFC_1123_DATE_TIME.
That pre-defined formatter already has the appropriate English-based locale required by the RFCs’ specifications. So no need to specify a Locale object here.
String input = "Wed, 20 Feb 2019 07:14:06 +0100" ;
DateTimeFormatter f = DateTimeFormatter.RFC_1123_DATE_TIME ;
OffsetDateTime odt = OffsetDateTime.parse( input , f ) ;
See this code run at Ideone.com.
2019-02-20T07:14:06+01:00
ISO 8601
Modern protocols use ISO 8601 rather than this outdated format. The java.time classes use ISO 8601 formats by default when parsing text or formatting a date-time instance.
I suggest you educate the publisher of your data about the virtues in using only ISO 8601 standard formats for communicating date-time values textually.

Parse String date of format yyyy-MM-dd to java.util.Date of format yyyy-MM-dd

We are using Java8 in our project.I have startDate in String format "2021-12-31" which I am receiving from from an 3RD party.
I have to pass it to our consumer via our model.Model accepts java.util.Date and the format should be yyyy-MM-dd.
I wrote the below code:
String strDate="2021-12-31";
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
java.util.Date parsedDate=(Date)df.parse(strDate);
Expected output : parsedDate = 2021-12-31
Actual Output: parsedDate= Tue Dec 07 00:00:00 GMT +5.30 2021.
Please help.
No, Tue Dec 07 00:00:00 GMT +5.30 2021 could not be the result of your code. Even accounting for time zone issues, the result could not be different by weeks. Please take more care when posting here, to not waste people's time.
The actual results of your code will be something more like the following. See for yourself.
Fri Dec 31 00:00:00 GMT 2021
Or, setting the JVM’s current default time zone to Asia/Kolkata:
Fri Dec 31 00:00:00 IST 2021
Notice that those two results are different moments, several hours apart. The day starts earlier in India than at UTC/GMT prime meridian. So the results of this code vary by the current default time zone — not good!
java.time
You are using terrible date-time classes that were years ago supplanted by the modern java.time classed defined in JSR 310.
Your input string complies with the ISO 8601 standard used by default in the java.time classes when parsing/generating text. So no need to specify a formatting pattern.
For a date-only value, without time of day, and without time zone or offset-from-UTC, use LocalDate.
LocalDate ld = LocalDate.parse( "2021-12-31" ) ;
You said:
Model accepts java.util.Date and the format should be yyyy-MM-dd
Well, (a) that is unfortunate, (b) a Date object does not have a "format", it has a date-time value rather than text, and (c) a java.util.Date represents a moment, a specific point on the timeline rather than a date-only. A Date object represents a date with time-of-day as seen in UTC (an offset from UTC of zero hours-minutes-seconds).
The best solution is to fix your design to use proper types.
If you cannot fix the faulty design and must employ a hack, then perhaps you could use the first moment of the day on that date as seen in UTC.
ZonedDateTime zdt = ld.atStartOfDay( ZoneOffset.UTC ) ;
Instant instant = zdt.toInstant() ;
Convert from modern class to legacy class by calling new conversion methods added to the old classes.
java.util.Date d = Date.from( instant ) ;
Dump to console.
System.out.println( "ld.toString(): " + ld ) ;
System.out.println( "zdt.toString(): " + zdt ) ;
System.out.println( "instant.toString(): " + instant ) ;
System.out.println( "d.toString(): " + d ) ;
See this code run live at IdeOne.com.
ld.toString(): 2021-12-31
zdt.toString(): 2021-12-31T00:00Z
instant.toString(): 2021-12-31T00:00:00Z
d.toString(): Fri Dec 31 00:00:00 GMT 2021

convert java.util.Date to java.util.Date with different formating in JAVA [duplicate]

This question already has answers here:
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
display Java.util.Date in a specific format
(11 answers)
Closed 2 years ago.
I get Date as java.util.Date(not String) : (java.util.Date) Mon Jul 13 00:00:00 IST 2020
I want to convert it to : 2020-07-13T00:00 format==>("yyyy-MM-dd'T'HH:mm") but as DATE not String.
I tried following code:
Date scheduleDate=details.getScheduledDate(); // This value is fetched from object passed-- [scheduleDate = (java.util.Date) Mon Jul 13 00:00:00 IST 2020]
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
sd.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
String dateFormat=sd.format(scheduleDate); //Here I get [dateFormat = (java.lang.String) "2020-07-13T00:00"]
Date date = sd.parse(dateFormat); //[date = (java.util.Date) Mon Jul 13 00:00:00 IST 2020]
I observed that string format has correct(as expected ) value but the value changes back when I convert it to java.util.date.
Does java.util.Date support yyyy-MM-dd'T'HH:mm format ?
If yes, Can anyone suggest me with any good approach/direction/topics/library to look into.
Thank You..
tl;dr
Convert from legacy class to modern class. Adjust from UTC to a time zone. Generate text in standard ISO 8601. We omit the context of time zone or offset in our output because you so requested, against my recommendation.
myJavaUtilDate
.toInstant()
.atZone( ZoneId.of( "Asia/Kolkata" ) )
.truncatedTo( ChronoUnit.MINUTES )
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
I expect using UTC and including the offset would be wiser.
myJavaUtilDate
.toInstant()
.toString()
Details
Date-time objects do not have a format, only text has a format.
Use java.time classes, never java.util.Date.
Convert your legacy Date object to its modern replacement, java.time.Instant.
Instant instant = myJUDate.toInstant() ;
Adjust from UTC to your desired time zone.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Apparently you do not care about the the second of minute. So let’s truncate that to zero seconds.
ZonedDateTime zdt = zdt.truncatedTo( ChronoUnit.MINUTES ) ;
Generate text in your desired format. Java comes bundled with a formatter already defined for your format.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;
I showed that format because asked. But I do not recommend it. That format fails to indicate a time zone or offset-from-UTC. So if it says noon, the reader does not know if that means noon in Tokyo Japan 🇯🇵, noon in Toulouse France 🇫🇷, or noon in Toledo Ohio Us 🇺🇸 — three very different moments, several hours apart.
When communicating a moment, a specific point on the timeline, textually it is usually best to do so in UTC. And use ISO 8601 standard formats. Commonly a Z is placed on the end to indicate UTC, an offset of zero hours-minutes-seconds.
Instant instant = zdt.toInstant() ;
String output = instant.toString() ;

converting from string to date object not displaying expected result [duplicate]

This question already has answers here:
How to Parse Date from GMT TimeZone to IST TimeZone and Vice Versa in android
(4 answers)
SimpleDateFormat returns wrong time zone during parse
(2 answers)
DateFormat parse - not return date in UTC
(1 answer)
Closed 3 years ago.
I searched for solutions but still not working ,I'm trying to convert the date object's local timezone to UTC +0 , but when i format the date object to UTC it's working . but when I want to convert the converted string to date again, the format changes and UTC goes back to GMT+8 before i store it in the fire store. what is the problem in the code?
this is the current date object that i get
Calendar time = Calendar.getInstance();
time.setTimeZone(TimeZone.getTimeZone("UTC"));
Date current_time = time.getTime();
if printed
Thu Aug 22 10:09:55 GMT+08:00 2019
then i convert it to UTC
String dismissal_time_firestore;
Log.i(TAG, "Current time when swiped from phone time.getTime() "+current_time);
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
dismissal_time_firestore = dateFormat.format(current_time);
got this
Thu, 22 Aug 2019 02:09:55 +0000
but then when i convert this string to a date object
try {
current_time = dateFormat.parse(dismissal_time_firestore);
} catch (ParseException e) {
e.printStackTrace();
}
i got this
Thu Aug 22 10:09:55 GMT+08:00 2019
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
Your main problem is not understanding that the Date::toString method lies to you. It dynamically applies the JVM’s current time zone to the moment in UTC while generating the text. One of many reasons to never use this class.
Get current moment in UTC.
Instant instant = Instant.now() ;
View that moment as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Generate text for display to user.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ;
String output = zdt.format( f ) ;
You talk about parsing formatted strings. Bad idea. Think of textual representations of date-time values only as outputs, not inputs. Collecting date-time inputs should be done by using date-time widgets, not typed text.
When storing or exchanging date-time values as text, always use ISO 8601 standard formats. The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify any formatting pattern. Just call parse/toString. Example: Instant.now().toString() and Instant.parse( "2020-01-23T12:34:56.123456Z" ).
I cannot help further as you did not really say what you were trying to accomplish.
All of this has been covered many many times on Stack Overflow. So search to learn more. And search before posting.

Java - Subtract Days from date [duplicate]

This question already has answers here:
How to subtract n days from current date in java? [duplicate]
(5 answers)
Closed 7 years ago.
I'm trying to subtract 5 days from a date which comes in as a string initially.
I have had a look at some of the other posts on this subject but the result i get from the code is always incorrect. The main problem is that the year value does not seem to change when the days are subtracted for example - 2012-01-01 subtract 5 days gives me 'Jan 27 2012' using this code -
cal.add(Calendar.DATE, -5);
Please help.
Did you know that, in Java, month 1 is actually February?
Date februaryTheFirst = new Date(2012,1,1); // equals 2012-02-01
This might explain what you are seeing. If you want to instantiate 2012-01-01 instead, you should do:
Date firstDayOf2012 = new Date(2012,0,1); // this is 2012-01-01
Exactly the same thing happens when dealing with Calendar:
Calendar.getInstance().set(2012,0,1); // 2012-01-01
Be sure to check the documentation for Date(int, int, int) and Calendar.set(int, int, int). Also, you could check the way you are parsing the string. If you use SimpleDateFormat.parse(...), things can be easier.
Strange, isn't it? Go figure... Just as a fun fact, IntelliJ's documentation annotates this second parameter, month, with #MagicConstant, to remember the programmer that there's something very strange going on.
Calendar.FEBRUARY is 1 and five days before 1 Feb 2012 was 27 Jab 2012.
Your implementation is correct and you are getting the correct value aslo.
Calendar's Months started with 0
0 = Jan
1 = Feb
so subtracting 5 days from 2012-01-01 will definitely returns you Jan 27 2012
something is here also which will helps you Why is January month 0 in Java Calendar?
Joda-Time
The Joda-Time 2.7 library makes this work much easier. Just call the minusDays method.
String input = "2012-01-01";
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( input, zone );
DateTime then = now.minusDays( 5 );
DateTimeFormatter formatter = DateTimeFormat.forStyle( "FF" ).withZone( zone ).withLocale( Locale.CANADA_FRENCH );
String output = formatter.print( then );
If you want the beginning of the day, add a call to withTimeAtStartOfDay. This is unnecessary in your case, when parsing a date-only string with no time-of-day.
DateTime dateTimeAtStartOfDay = new DateTime( input, zone ).withTimeAtStartOfDay();
If you want only date without time-of-day or time zone, use LocalDate instead of DateTime.
LocalDate then = new LocalDate( "2012-01-01" ).minusDays( 5 );
If you need to convert to the old java.util.Date, call toDate on the DateTime.
java.time
Java 8 has a new package, java.time. These new classes were inspired by Joda-Time but were re-architected. Both java.time and Joda-Time can solve this particular problem equally well.
Use:
cal.add(Calendar.DAY_OF_MONTH, -5)
EDIT: sorry. DAY_OF_MONTH is a synonym to DATE. Instead of 1 use Calendar.JANUARY.
This a segment of code that is working on my pc. first you have to get the calendar instance the perform your calculation.
Calendar cal = Calendar.getInstance();
System.out.println("Today : " + cal.getTime());
// Subtract 300 days from the calendar
cal.add(Calendar.DATE, -300);
System.out.println("300 days ago: " + cal.getTime());
This is the output that you will get:
Today : Wed Oct 17 10:41:23 EET 2012
300 days ago: Thu Dec 22 10:41:23 EET 2011

Categories

Resources