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 build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023