java – Parsing and changing the date in a custom format

Question:

There is a string with date and time in a specific format

String date = "Tue Sep 11 08:28:59 EDT 2018";

At the exit I want to get

11.09.2018 08:28

But I get

10.09.2018 15:28

Format

"EEE MMM d HH:mm:ss z yyyy"

I want to parse the date and display it in a different format

"dd.MM.yyyy HH:mm"

My implementation:

public static String getTime(String time, String inFormat, String outFormat) throws ParseException {
    Date date = new Date();
    SimpleDateFormat simpleFormet = new SimpleDateFormat(inFormat); 
    SimpleDateFormat simpleFormet2 = new SimpleDateFormat(outFormat); 
    date = simpleFormet.parse(time)
    return simpleFormet2.format(date);
}

The problem is that the time is always reset to the current one, tell me how to do it right.

Answer:

In order for the date and time to be the same as originally, you need to get the z value in the original string. This can be done in a variety of ways, including using Joda DateTime .

String timeZone = date.substring(20,3);
if ("EDT".equals(timeZone)) timeZone = "GMT-4";
simpleFormet2.setTimeZone(TimeZone.getTimeZone(timeZone)); 
Scroll to Top