divinedragon divinedragon -4 years ago 74
Java Question

Format a String to a Fixed Date at UTC+0 in Java

I want to convert a String date -

2017-01-01
to
java.util.Date
with
UTC+0
. So, what I am expecting is.


"2017-01-01" -> 2017-01-01T00:00:00 UTC+0100



Here is how I am trying to do, but as my default Timezone is UTC+1, I am getting that 1 hour added to the Date.

Date d = Date.from(Instant.parse("2017-01-01T00:00:00Z"));

SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss 'UTC'ZZZZZ");

String output = sf.format(d);

System.out.println(output);


Here is the output:

2017-01-01T01:00:00 UTC+0100


Can somebody help?

Answer Source

You can set the timezone first and then format it.

sf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sf.parse(d);

And now format as per your requirements:

String output = sf.format(date);
System.out.println(output);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download