Sunday, March 4, 2012

How do I convert string to Date in GMT timezone in Android?


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 theTimeZone of the DateFormat object into GMT.

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();
        }
    }
}

Below is the output.....

Today = Sun, 12 Feb 2012 00:00:00 GMT

No comments:

Post a Comment