Question

I am working on a project which requires me to create a Date value by setting it to a particular timezone .

I have used the following code

Date formatter1 = new Date(HttpDateParser.parse("2013-08-02 11:00:00"));
System.out.println("Date dd formatter1"+formatter1);

Result as follows:

Fri Aug 02 16:30:00 Asia/Calcutta 2013

After parsing, it is giving me time according to device time zone ... adding 5:30 automatically if device time zone is set to India Kolkata.

I want result to be as :

Fri Aug 02 11:00:00 Asia/Calcutta 2013

I mean it should not add the offset as reference to GMT .

How could I work upon this code to set the data required to me as per the Timezone and not change it internally ?

Was it helpful?

Solution

One problem is that your original date string:

2013-08-02 11:00:00

does not include time zone information. So, it is being interpreted as a GMT time. Which then means that, displayed in Calcutta time, it will be

Fri Aug 02 16:30:00 Asia/Calcutta 2013

You want to specify that 11:00 is already in Calcutta time. To do that, use one of the formats defined in the HttpDateParser documentation:

  // we make sure to specify time zone information "+05:30"!
  long timeSinceEpoch = HttpDateParser.parse("2013-08-02T11:00:00+05:30");

  Date date = new Date(timeSinceEpoch);
  System.out.println("Date: " + date);
  
  // use this to slightly change the date formatting ... same time zone
  String pattern = "yyyy-MM-dd hh:mma";
  SimpleDateFormat formatter = new SimpleDateFormat(pattern);
  String formattedDate = formatter.formatLocal(timeSinceEpoch);

  System.out.println("SimpleDateFormat: " + formattedDate);

Note: that in addition to adding "+5:30" to the time string, you have to replace a space after the date with a 'T'.

This code will output:

[0.0] Date: Fri Aug 02 11:00:00 Asia/Calcutta 2013

[0.0] SimpleDateFormat: 2013-08-02 11:00am

if the device's time zone is actually set to Calcutta (Kolkata +5.5).

References

Have a look at this answer on Stack Overflow.
and maybe this one, too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top