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?
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?
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();
}
can't you simply convert the date with simpleDateFormat?
then you just define the structure of your incoming date like that (df) and transform it to the form you want (df):
private static DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
private static DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy 'at' HH:mm");
public void setyourDate(String yourDate) {
Date date2;
yourDate = getyourDate() + "" + yourDate;
try {
date2 = df.parse(yourDate);
yourDate = df2.format(date2);
} catch (ParseException e) {
}
this.yourDate = yourDate;
}
does it make sense?
This is an old question, but I want to write my answer. Assume, the timestamp you get from SQL is like the following format: yyyy-MM-dd'T'HH:mm:ss
public static Date convertStringToDate(String strDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("CST"));
return sdf.parse(strDate);
}
Related
I'm parsing the times from AD. There are two formats, i.e., YMD LDAP timestamps for whenCreated, whenChanged, 18-digit LDAP/FILETIME timestamps for lastLogonTimestamp, pwdLastSet, etc. Because I need to analyze the data upon the time. It makes sense to get local time. Here are the two functions that I wrote to parse the two different formats. The calculation in the second function I referenced from Convert 18-digit LDAP Timestamps To Human Teadable Date Using Java
public static String parseLdapDate(String ldapDate) {
String[] parts = ldapDate.split("[.]");
String dateTimePart = parts[0]; //take the date string before .0Z
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT")); //Z means UTC time, to the local timezone
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date tempDate = sdf.parse(dateTimePart); //parse the string to a date
return formatter.format(tempDate); //format it as what we want
} catch (ParseException ex) {
System.out.println("Parsing LDAP Date exception \n");
ex.printStackTrace();
}
return null;
}
public static String parseLdapTimestamp(String ldapTimestamp) {
long nanoseconds = Long.parseLong(ldapTimestamp); // 100 nanoseconds
long mills = (nanoseconds/10000000); // To seconds
long unix = (((1970-1601)*365)-3+Math.round((1970-1601)/4))*86400L;
long timeStamp = mills - unix;
Date date = new Date(timeStamp*1000L); // To milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.format(date);
}
I have an example 20150520143936.0Z, which is converted to "2015-05-20 16:39:36".
For the example 131097986571852097, it is converted to "2016-06-07 18:44:17", while http://www.epochconverter.com/ldap tells me that it's the GMT time and the local time is "2016-06-07 20:44:17". I will get the local time if I comment the code of setting timezone.
So now I'm confused, sdf.setTimeZone(TimeZone.getTimeZone("GMT")); gives me local timezone or the universal time. I was thinking if AD stores whenCreated in the universal time, lastLogonTimestamp in local time. But in the functions I parse them as strings. There is no symbol about the timezone. If I comment this sentence in the second function, will I get local time for both attributes when I access an LDAP Directory in another place.
In the second case, you're constructing a Date and then telling it to format that date in UTC - whereas in the first case, you're parsing it in UTC, but formatting it in local time. You're already assuming that the timestamp is stored as a number of ticks since the Unix epoch, which is a time zone neutral format.
If the aim is to produce a string representation in local time, then you should remove the sdf.setTimeZone call. I would argue that a parse method should be returning a Date anyway though, rather than a String. Or better yet, return a java.time.Instant...
I've timestamp based on IST ( Indian Standard Time / GMT + 5:30 Hrs), My application shows last activity time based on device timestamp.
that is current time - activity timestamp. Its fine when the device timezone is IST.
For example,
Activity timestamp - 11/Feb/2016 09:00:00 AM
Current timestamp (IST) - 11/Feb/2016 10:00:00 AM
My Calculation = Current timestamp - Activity timestamp
So Application shows 1 hr ago
But the device timezone changed to some other like PHT for the same time (Philippine Time / GMT + 8 Hr)
Activity timestamp - 11/Feb/2016 09:00:00 AM
Current timestamp(PHT) - 11/Feb/2016 12:30:00 AM (plus 2:30Hrs compare with IST)
My Calculation = Current timestamp - Activity timestamp
So Application shows 3 hrs 30 mis ago
My problem is, How to get the IST time always using java? whatever the timezone, I need IST time.
I tried below code, When i change the value to IST but the timezone automatically changed to device timezone.
Please refer below URL for source code http://goo.gl/dnvQF5
SimpleDateFormat sd = new SimpleDateFormat(
"yyyy.MM.dd G 'at' HH:mm:ss z");
Date date = new Date();
// TODO: Avoid using the abbreviations when fetching time zones.
// Use the full Olson zone ID instead.
sd.setTimeZone(TimeZone.getTimeZone("GMT"));
String gmtDate = sd.format(date);
System.out.println("GMT --> " + gmtDate);
String istDate = gmtDate.replace("GMT", "IST");
System.out.println("After Replace -> " + istDate);
sd.setTimeZone(TimeZone.getTimeZone("IST"));
try {
Date istConvertedDate = sd.parse(gmtDate);
System.out.println("After Convert --> " + istConvertedDate);
} catch (ParseException ex) {
ex.printStackTrace();
}
I got output like
GMT --> 2016.02.11 AD at 05:20:07 GMT
After Replace -> 2016.02.11 AD at 05:20:07 IST
After Convert --> Thu Feb 11 00:20:07 EST 2016
Please help me to resolve this.
The class java.util.Date is only a thin wrapper around elapsed milliseconds since UNIX epoch (1970-01-01T00:00:00Z). Objects of this type don't carry any format or timezone information. Therefore every such object has completely lost the timezone information after parsing a text with timezone identifier or name using SimpleDateFormat.
What you observe and are confused about is the fact that the method toString() of this class uses a specific representation based on the system timezone.
Another thing: If you apply a string manipulation replacing "GMT" by "IST" (an ambivalent timezone name - Israel? India? Ireland?) then you effectively change the moment/instant while keeping the local time representation. Do you really want this?
If you want to preserve the timezone information which was originally parsed then you could use ZonedDateTime in the library Threeten-ABP or DateTime in the library Joda-Time-Android or ZonalDateTime in my library Time4A.
Try
public static void main(String[] args) {
SimpleDateFormat sd = new SimpleDateFormat(
"yyyy.MM.dd G 'at' HH:mm:ss z");
Date date = new Date();
// TODO: Avoid using the abbreviations when fetching time zones.
// Use the full Olson zone ID instead.
sd.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sd.format(date));
String gmtDate = sd.format(date);
System.out.println(gmtDate);
//Here you create a new date object
Date istDate= new Date();
sd.setTimeZone(TimeZone.getTimeZone("IST"));
String istDate=sd.format(istDate);
System.out.println(istDate)
}
This way the first printed time will be GMT and second will be ISD.
You can use java.util.Calendar
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("IST"));
this calendar contains current time in IST timeZone.
You can set timeStamp:
calendar.setTimeInMillis(timeStamp);
And get java.util.Date or time stamp
Date date = calendar.getTime();
Long timeStamp = calendar.getTimeInMillis();
Replace
sd.setTimeZone(TimeZone.getTimeZone("IST"));
to
TimeZone.setDefault(TimeZone.getTimeZone("IST"));
This question already has answers here:
Timezone conversion
(13 answers)
Closed 8 years ago.
I want to create an alarm application for FIFA 2014 world cup matches in which i have a server which stores the date and time for the matches in Brazil/Acre and my client is an android application and an android device may have any of the possible timezone so the my problem is i want to convert the Brazil/Acre timing to the local android device timing with different timezone and after lot of googled i came to know about joda data and time lib but it is too slow in android so please suggest any code that will work for me.
In my opinion Time class is the best for your job. Also it is Android API not general Java API.
Here I mentioned some of useful methods for your job:
void switchTimezone(String timezone)
Convert this time object so the time represented remains the same, but is instead located in a different timezone.
static String getCurrentTimezone()
Returns the timezone string that is currently set for the device.
And if you want to save a time in a timezone independed manner, you can convert to milliseconds (in UTC) by toMillis() method and then retrieve it by set(long millis) method.
If something is unclear please tell me!
UPDATE
Example:
long timeMillis = /* get time milliseconds form the server */
Time time = new Time();
time.set(timeMillis);
/* changing time zone */
time.switchTimezone(/* your desired timezone in string format */);
/* getting time as string */
String timeString = time.format("%Y%m%dT%H%M%S"); // you can change format as you wish
Here is a table for formatting times
You could use this code, which substracts the hour-difference between Brazil and the local timezone. Just replace yourDate with a Date-object.
//code...
yourDate.setTime(yourDate.getTime() - getDifferenceInMillis());
//code...
public int getDifferenceInMillis() {
// Local Time
int localMinute = Calendar.getInstance().get(Calendar.MINUTE);
int localHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
int localDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
// Brazil Time
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("Brazil/Acre"));
c.setTimeInMillis(new Date().getTime());
int brazilMinute = c.get(Calendar.MINUTE);
int brazilHour = c.get(Calendar.HOUR_OF_DAY);
int brazilDay = c.get(Calendar.DAY_OF_MONTH);
// Difference between Brazil and local
int minuteDifference = brazilMinute - localMinute;
int hourDifference = brazilHour - localHour;
int dayDifference = brazilDay - localDay;
if (dayDifference != 0) {
hourDifference = hourDifference + 24;
}
return (hourDifference * 60 + minuteDifference) * 60 * 1000;
}
You should store your date has a long or timestamp in your server. If you don't want you can anyway send your date as a long generate from your database date. Then create your calendar instance like that :
Calendar c = Calendar.getInstance();
c.setTime(new Date(yourdatelong));
You can have to multiplie and add some constant in your long. In java the definition is "the number of milisecond since 1970 1/1 00:00:00". It is differents in C#, for exemple ( number of nanoseconde from 1/1/1900, if I remenber well).
Like that you are sure to set the same date in all your device. When it is done, you just have to put the timezone that you want in your calendar to display the local time.
http://developer.android.com/reference/java/util/Calendar.html
You can have many option to manage time and display it in this class.
If dates are stored in server time zone (Brazil/Acre), you should load date time from DB, convert it to UTC time zone and send to client. On client side change UTC to local time zone:
Server side:
DateTime dateOnServer = // load date from db
DateTime dateUTC = dateOnServer.withZone(DateTimeZone.UTC); // convert to UTC
String dateAsStringUTC = dateUTC.toString("yyyy-MM-ddTHH:mm:ss");
// send 'dateAsStringUTC' to client
Client side:
String dateAsStringUTC = // receive date from server
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-ddTHH:mm:ss"); // parser for date
DateTime dateOnClient= dtf.parseDateTime(dateAsStringUTC);
// 'dateOnClient' will be in client time zone 'DateTimeZone.getDefault()'
I faced same problem like you...
I got the solution using SimpleDateFormat
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsed = format.parse("2011-03-01 15:10:37"); // => Date is in UTC now
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
destFormat.setTimeZone(tz);
String result = destFormat.format(parsed);
this may help you..
I m facing a problem:I want to get current time of GMT TimeZone in long.
I m using the following code as given below:
TimeZone timeZoneGmt = TimeZone.getTimeZone("GMT");
long gmtCurrentTime = getCurrentTimeInSpecificTimeZone(timeZoneGmt);
public static long getCurrentTimeInSpecificTimeZone(TimeZone timeZone) {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(timeZone);
long finalValue = 0;
SimpleDateFormat sdf = new SimpleDateFormat(
"MMM dd yyyy hh:mm:ss:SSSaaa");
sdf.setTimeZone(timeZone);
Date finalDate = null;
String date = sdf.format(cal.getTime());
try {
finalDate = sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finalValue = finalDate.getTime();
return finalValue;
}
As given in, above method
while formatting
String date = sdf.format(cal.getTime());
I m getting correct current time in GMT but as i do parsing by following code:
finalDate=sdf.parse(date);
Date got changed from current GMT time to 15:35:16 IST 2013 that is current time of my system.
I tried with Calendar as well in another way:
TimeZone timeZoneGmt=TimeZone.get("GMT");
Calendar calGmt = Calendar.getInstance();
calGmt.setTimeZone(timeZoneGmt);
long finalGmtValue = 0;
finalGmtValue = calGmt.getTimeInMillis();
System.out.println("Date......" + calGmt.getTime());
but still getting date as current time of my System Thu Jan 23 15:58:16 IST 2014 Not getting GMT current time.
You've misunderstood how Date works. A Date doesn't have a time zone - if you use Date.toString() you'll always see the default time zone. The long value in a Date is purely the number of milliseconds since the Unix epoch: it doesn't have any concept of time zone or calendar system.
If you want to represent a date and time in a particular time zone and calendar, use Calendar instead - but for getting "the current date and time as a long" you can just use System.currentTimeMillis(), which again does not have anything to do with the system time zone.
Additionally, even if you did want to do manipulation like this, you shouldn't be using string conversions. You're not conceptually performing any string conversions, so why introduce them?
If your aim is to display (as a string) the current date and time in a particular time zone, you should just use something like:
Date date = new Date(); // This will use the current time
SimpleDateFormat format = new SimpleDateFormat(...); // Pattern and locale
format.setTimeZone(zone); // The zone you want to display in
String formattedText = format.format(date);
When working with date and time APIs - particularly bad ones like the Java Calendar/Date API - it's very important that you understand exactly what each value in your system represents.
I have a date that I get from a server formatted in EST like this
05/07/2012 16:55:55 goes month/day/year then time
if the phone is not in EST how can I convert it to the timezone the phone is in?
it would be not problem if I got the time in milliseconds but I dont
EDIT:
ok now the time is not correct when formatting
String sTOC = oNewSTMsg.getAttribute("TOC").toString();
String timezoneID = TimeZone.getDefault().getID();
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("EST"));
String newtimezoneID = TimeZone.getDefault().getID();
Date timestamp = null;
try{
timestamp = format.parse(sTOC);
format.setTimeZone(TimeZone.getDefault());
timezoneID = format.format(timestamp);
}catch(ParseException e){
}
I convert it to "EST" then format that time to the default TimeZone but the time is always off by an hour, not sure why?
Use the following code to get a UNIX timestamp:
String serverResp = "05/07/2012 16:55:55";
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
Date date = format.parse(serverResp);
Now you have the timestamp, which you know how to use.
Here's another question which covers conversion, in case you are curious: Android Convert Central Time to Local Time
Use the DateFormat class to parse the String into a Date. See the introduction to the API document here... http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html
You can then create a Calendar for the Date...
Calendar cal = Calendar.getInstance().setTime(date);
And then you can change the timezone on the Calendar to a different timezone using setTimezone(). Or just get the time in milliseconds, using getTimeInMillis()
Using the Calendar, Date, and DateFormat classes should put you in the right direction.
See the Calendar documentation here... http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html