Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Convert Central Time to Local Time

I have a MySql database that stores a timestamp for each record I insert. I pull that timestamp into my Android application as a string. My database is located on a server that has a TimeZone of CST. I want to convert that CST timestamp to the Android device's local time.

Can someone help with this?

like image 634
northdig Avatar asked Dec 07 '22 04:12

northdig


2 Answers

Use getTimeZone.getDefault combined with according to the Android documentation.

public static synchronized TimeZone getDefault ()

Gets the default time zone. Returns the default time zone.

So since you know that CST is -6:00 from GMT, and you get a local timezone saying the user is +9:00 (Japan), you'd know to adjust your MySQL DB times by +15 hours (9 - (-6)). Or if they are in Miami (EST, -5), you would adjust by adding one hour (-5 - (-6)). If the are in Portland, Oregon, (PST -8), you would subtract 2 hours (-8 -(-6)).

So really you just need to get the local timezone offset and feed it into the basic equation: TimeZone.getDefault + 6 and you'll know what to add or subtract to your local DB. (+6 since -(-6) always works out to +6).

If I knew the first thing about writing Java, I'd go the extra step and write a bit of sample code, but alas, I'm only smart enough for scripts.

Crude Attempt at Java

I already said I have no idea how to do Java or object oriented anything, right?

Here's a crude attempt from just poking around the Android documentation. Any fine points or simple "Not even close" remarks welcome. Bear in mind that I figured out the right method and class already just from a quick search and I came up with a simple equation for converting the timezone offset for anywhere to CST, so I'm not a dunce, just someone who doesn't know when to leave well enough alone. Anyway, crude attempt:

System now = System.currentTimeMillis (); //Gets current local time in ms
TimeZone local_tz = TimeZone.getDefault();  //Gets current local TZ of phone
tz_offset_gmt = local_tz.getOffset(now)/3600000; // Get Offset in ms, divide by 3600000
tz_offset_cst = tz_offset_gmt + 6;  // add offset to 6 to get current TZ offset to CST.

Anywhere close to how to do this in java?

like image 98
Anthony Avatar answered Dec 11 '22 09:12

Anthony


Suppose you have a string of date in CST, parse it with timezone CST and then format it with the default timezone on your android.

String s = "2011-01-01 12:00:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("CST"));
Date timestamp = null;
try {
    timestamp = df.parse(s);
    df.setTimeZone(TimeZone.getDefault());
    System.out.println(df.format(timestamp));
} catch (ParseException e) {
    e.printStackTrace();
}
like image 30
David Avatar answered Dec 11 '22 10:12

David