user1851366
user1851366

Reputation: 346

How to set time by location Android

I have a date in format (for example) "28-11-2014 00:00", and i want to show in android by location. I mean, automatcliy system check location and format for that location.

Example:

In differente countries users will see different texts. Someone can help me? Anyway, for testing that in emulator, what i can to do for change system locale?

thanks

Edit: I posted a solution below

Upvotes: 0

Views: 190

Answers (3)

user1851366
user1851366

Reputation: 346

I got my own answer! Here is the solution

    //my format
    String format = "yyyy-MM-dd HH:mm";
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    sdf.setTimeZone(TimeZone.getTimeZone("CET"))
    //my date
    String dateInString = "2014-11-28 11:00";
    Date date = sdf.parse(dateInString);

    //my solution
    sdf.setTimeZone(TimeZone.getDefault());
    System.out.format("%30s %s\n", format, sdf.format(date));
    //example
    sdf.setTimeZone(TimeZone.getTimeZone("CET"));
    System.out.format("%30s %s\n", format, sdf.format(date));
    sdf.setTimeZone(TimeZone.getTimeZone("PST"));
    System.out.format("%30s %s\n", format, sdf.format(date));

Upvotes: 1

Chk0nDanger
Chk0nDanger

Reputation: 1231

I have done this with Google TimeZone API.

curl -X GET https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510&timestamp=1331161200&key=API_KEY

{
    "dstOffset" : 0.0,
    "rawOffset" : -28800.0,
    "status" : "OK",
    "timeZoneId" : "America/Los_Angeles",
    "timeZoneName" : "Pacific Standard Time"
}

You can get local time with following code.

TimeZone timeZone = new SimpleTimeZone((int) getRawOffset(), getTimeZoneId());
Calendar cal = Calendar.getInstance();
cal.setTimeZone(timeZone);
String localDate = new SimpleDateFormat("MM-dd-yyyy HH:mm").format(cal.getTime());

Upvotes: 2

David Kasabji
David Kasabji

Reputation: 1069

Have you tried this:

Most applications will use TimeZone.getDefault() 
which returns a TimeZone based on the time zone where the program is running.

With this you can get the Time Zone from which the App is running. Or do you want to display on your App Time zones all over the world?

You could then import them manually by checking the data on Internet or try googling for API's that include such things.

Upvotes: 2

Related Questions