Hiren Gujarati
Hiren Gujarati

Reputation: 1049

Date/Time conversion to local time

See the below code

Date date1 = new Date(HttpDateParser.parse(dateString);
int offset = TimeZone.getTimeZone("GMT+5:30").getRawOffset();
date1.setTime(date1.getTime() + offset);
String pattern = "yyyy-MM-dd hh:mma";
SimpleDateFormat date = new SimpleDateFormat(pattern);
String dateNow = date.format(date1);

It converts fine to indian standard time in simulator. When i try to use in device, the time remain unchanged.

Upvotes: 2

Views: 1825

Answers (2)

Hiren Gujarati
Hiren Gujarati

Reputation: 1049

 Parses a date string and returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.

But what happen if i pass milliseconds to Date() function. It automatically gives date converting to user's local timezone. Cheers.

The below code have done everything fine.

 Date date1 = new Date(HttpDateParser.parse((String)kValue))

The date1 already converted to user's local timezone.

Upvotes: 0

Michael Donohue
Michael Donohue

Reputation: 11876

HttpDateParser.parse says in the docs:

Parses a date string and returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.

If you want to display the time in the device's own timezone, you don't need to do all that timezone conversion, just use SimpleDateFormat directly:

long timeSinceEpoch = HttpDateParser.parse(dateString);
String pattern = "yyyy-MM-dd hh:mma";
SimpleDateFormat date = new SimpleDateFormat(pattern);
String dateNow = date.formatLocal(timeSinceEpoch);

Upvotes: 2

Related Questions