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
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023