get helsinki local time regardless of local time z

2019-07-03 04:03发布

i really need to get Helsinki and Moscow current time using javascript but regardless of local timezone. I wonder how to do that? Maybe anyone has an example?

The format would be:

November 1, 2011 21:31:00

thank you.

2条回答
看我几分像从前
2楼-- · 2019-07-03 04:20

The following function works when you know the offset ahead of time:

var MOSCOW_OFF = 4; // hours
var MONTHS = ["January", "February", "March", "April", "May", "June", "July", 
              "August", "September", "October", "November", "December"];

// desired format => November 1, 2011 21:31:00
function getLocalTime(offset) {
    var d = new Date();
    d.setTime((new Date().getTime()) + 
              (d.getTimezoneOffset() * 60 * 1000) + // local offset
              (1000 * 60 * 60 * offset)); // target offset
    return MONTHS[d.getMonth()] + " " + d.getDate() + ", " + 
            d.getFullYear() + " " + d.toTimeString().split(" ")[0];
}

getLocalTime(MOSCOW_OFF); // => "November 2, 2011 01:22:27"

The above will always work for Moscow, which no longer observes a Daylight Savings Time, but you'd need to be aware of what time of year it is to make an equivalently generic solution for Helsinki.

查看更多
Bombasti
3楼-- · 2019-07-03 04:22
// create Date object for current location
d = new Date();
// convert to msec since Jan 1 1970
localTime = d.getTime();
// obtain local UTC offset and convertto msec
localOffset = d.getTimezoneOffset() * 60000;
// obtain UTC time in msec
utc = localTime + localOffset;
// obtain and add destination's UTC time offset
// for example, Paris
// which is UTC + 1.0 hours
offset = 1.0;  
paris = utc + (3600000*offset);
// convert msec value to date string
nd = new Date(paris);
document.writeln("Paris time is " + nd.toLocaleString() + "<br>");

(Sorry, don't know Helsinki offset, probably 2?)

Note that a negative return value from getTimezoneOffset() indicates that the current location is ahead of UTC, while a positive value indicates that the location is behind UTC.

[edit]
This may work better: (note that you will have to manipulate the format yourself from the recv'd helsinki variable

function getTZTime (tzOffset) {
   local = new Date(); 
   off = ( local.getTimezoneOffset() ) * 60 * 1000;
   timeStamp = local.getTime() + off; 
   off += 1000 * 60 * 60 * tzOffset;
   nd = new Date();
   nd.setTime( timeStamp );
   return (nd);
}

helsinki = getTZTime (2); // Helsinki is 2 TZ's from GMT

[/edit]

查看更多
登录 后发表回答