convert Date to RFC Date time

285 views Asked by At

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.

1

There are 1 answers

3
Basil Bourque On

Apparently you want to:

  1. Parse a string representing a date.
  2. 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, missing 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

By the way, this format is outmoded. Modern protocols adopt ISO 8601 for date-time formats in text.