How do I convert string to Date in GMT timezone?

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.example.text;

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("Sun, 12 Feb 2012 00:00:00 GMT");
            System.out.println("Today = " + df.format(today));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply