Search code examples
androidiostimetimezonetitanium

Titanium - How can I get always a specific timezone and get only the time?


I'm trying to get always an specific time of a specific timezone

e.g: Sao Paulo(-3)

I've tried this code that I found searching here on stackoverflow:

// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(city, offset) {

    // create Date object for current location
    d = new Date();

    // convert to msec
    // add local time zone offset 
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);

// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));

// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();

}

// get Sao Paulo time
Ti.API.info(calcTime('Sao Paulo', '-3'));

on my Ti.API.info() I get this as response: The local time in Sao Paulo is August 6, 2013, 3:31:52 PM GMT-03:00... There's a way to get only 3:31:52 ? Besides... as this function says... it get always the local time and them show what's the time on that timezone... BUT someone knows how can I get always Sao Paulo's time whitout giving the local time ? So if the user change their time on phone it won't change the Sao Paulo's time.

Thanks


Solution

  • If you are just talking about JavaScript, then please see this answer. However, my guess is that Titanium has its own way of mapping the native iOS or Android time zone APIs into JavaScript. If not, it should. I don't know enough about Titanium to answer on this point further.

    Do keep in mind that a time zone cannot be represented by just an offset. See "Time Zone != Offset" in the timezone tag wiki.

    In particular, Sao Paulo is represented by the America/Sao_Paulo time zone in the IANA time zone database. This zone alternates between -3 and -2, as shown here. You cannot simply pass in -3 and expect it to know what to do.