david david - 1 year ago 49
Java Question

How to format a date in a particular format which has timezone in the output

I have a date in string format like this. It is coming from some other souce in the below format and I cannot change that:

2025-08-08T15%3A41%3A46


I have to convert above string date in this format now:

Fri Aug 08 15:41:46 GMT-07:00 2025


So below is what I have tried:

String decodedDate = URLDecoder.decode("2025-08-08T15%3A41%3A46", "UTF-8");
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
Date date = dateParser.parse(decodedDate);
System.out.println(date);


And this is what it prints out on the console. It prints out
PDT
instead of
GMT-07:00
. How can I get that?

Fri Aug 08 15:41:46 PDT 2025


Also I am working with Java 7 and I can use
joda-time
library as well. This conversion method can be called by multiple threads.

In the desired output it is printing out
GMT-07:00
so how can I get the timezone also in my code?

Update:-

How about doing this way?

SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
TimeZone.setDefault(TimeZone.getTimeZone("GMT-07:00"));
String decodedDate = URLDecoder.decode("2025-08-08T15%3A41%3A46", "UTF-8");
Date date = dateParser.parse(decodedDate);
System.out.println(date.toString());

Answer Source
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
String decodedDate = URLDecoder.decode("2025-08-08T15%3A41%3A46", "UTF-8");
Date date = dateParser.parse(decodedDate);

//Decode the given date and convert to Date object

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z-07:00 yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

System.out.println(sdf.format(date)); // set the timezone and print in the desired format

Output:

Fri Aug 08 07:41:46 GMT-07:00 2025

Update: As suggected by KevinO, a better way to do is

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT-0700"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download