Gödel77
Gödel77

Reputation: 839

SimpleDateFormat for a HTTP Date

I can parse a HTTP Date but I don't get what I want, i.e. in this Example

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;


public class Example01 {

    public static void main(String[] argv) throws Exception {
        Date date = null;
        String dateValue  = "Tue, 27 Jan 2015 07:33:54 GMT";
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));


        System.out.println("date = " + date);
    }

}

And the output I got is date = Tue Jan 27 08:33:54 CET 2015.

What should I change, in order to get date = Tue, 27 Jan 2015 08:33:54 GMT?

Upvotes: 1

Views: 2055

Answers (1)

Daniel Le
Daniel Le

Reputation: 1830

There are a few problems with your code:

  1. You never initialize date to anything other than null, thus System.out.println("date = " + date); will print date = null, not date = Tue Jan 27 08:33:54 CET 2015.
  2. The date string you provide is Tue, 27 Jan 2015 07:33:54 GMT, yet you ask the output to be Tue, 27 Jan 2015 08:33:54 GMT. The output is one hour later than the date string provided. I'm going to assume it's a typo on your side and you actually want the former as output.
  3. You didn't use the SimpleDateFormat dateFormat object that you've got when printing out the date. System.out.println("date = " + date); calls the Date.toString() method which uses your local timezone.

A working version is:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;


public class Example01 {
    public static void main(String[] argv) throws Exception {
        Date date = null;
        String dateValue  = "Tue, 27 Jan 2015 07:33:54 GMT";

        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);

        date = dateFormat.parse(dateValue);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

        System.out.println("date = " + dateFormat.format(date));
    }
}

Upvotes: 2

Related Questions