Reputation: 4487
I'm currently a developing a sync module for one of my applications. I'm syncing the records between local and server based on LastUpdated time, which is nothing but a timestamp. The server is of Singapore, so how can I set the timezone to Singapore in my Android application?
I have tried,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("VST") );
and,
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("Asia/Singapore"));
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
Still no luck.
Or is there any way I can set the common timezone for both local and server? Server side language is ASP.Net
Upvotes: 2
Views: 7735
Reputation: 338604
When doing anything significant with date-time work, you should avoid the java.util.Date and java.util.Calendar classes as they are notoriously troublesome, confusing, and flawed. Instead use the Joda-Time library which does work in Android.
Your string input is close to standard ISO 8601 format. Just replace the SPACE with a T
. Then pass the result to the constructor of DateTime
along with a DateTimeZone
object representing the intended time zone of that string. Search StackOveflow for hundreds of examples.
As Elliott Frisch commented, on the server-side you should be working and storing date-time values all in UTC. Convert to local zoned values only when expected by the user in the user interface.
The server itself should be set to UTC, or if not possible then set to Reykjavík Iceland. But your programming should never assume the server is so set. Your programming should always specify the desired time zone.
Search StackOverflow for hundreds of examples and discussion of these points.
Upvotes: 2
Reputation: 4487
Finally, this is how I solved it.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
TimeZone tz = TimeZone.getTimeZone("Asia/Singapore");
sdf.setTimeZone(tz);
java.util.Date date= new java.util.Date();
Timestamp local = new Timestamp(date.getTime());
String strDate = sdf.format(date);
System.out.println("Local in String format " + strDate);
Upvotes: 1
Reputation: 201447
Your SimpleDateFormat
example is almost correct. I believe you want SGT
for Singapore and you need to call DateFormat.format(Date)
. You might also pass the TimeZone
to Calendar.getInstace(TimeZone)
like
TimeZone tz = TimeZone.getTimeZone("SGT");
sdf.setTimeZone(tz);
System.out.println(sdf.format(Calendar.getInstance().getTime()));
System.out.println(Calendar.getInstance(tz));
Upvotes: 3