The following code snippet convert a string representation of a date into a java.util.Date
object and the timezone is set to GMT. To parse the string so that the result is in GMT you must set the TimeZone
of the DateFormat
object into GMT
.
package org.kodejava.joda;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class WithTimezoneStringToDate {
public static void main(String[] args) {
// Create a DateFormat and set the timezone to GMT.
DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
// Convert string into Date
Date today = df.parse("Fri, 29 Oct 2021 00:00:00 GMT+08:00");
System.out.println("Today = " + df.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The code snippet above print the following output:
Today = Thu, 28 Oct 2021 16:00:00 GMT