Convert Utc Offset to Timezone or Date

Convert UTC offset to timezone or date

It can be done quite simply, by turning the offset into seconds and passing it to timezone_name_from_abbr:

<?php
$offset = '-7:00';

// Calculate seconds from offset
list($hours, $minutes) = explode(':', $offset);
$seconds = $hours * 60 * 60 + $minutes * 60;
// Get timezone name from seconds
$tz = timezone_name_from_abbr('', $seconds, 1);
// Workaround for bug #44780
if($tz === false) $tz = timezone_name_from_abbr('', $seconds, 0);
// Set timezone
date_default_timezone_set($tz);

echo $tz . ': ' . date('r');

Demo

The third parameter of timezone_name_from_abbr controls whether to adjust for daylight saving time or not.

Bug #44780:

timezone_name_from_abbr() will return false on some time zone
offsets. In particular - Hawaii, which has a -10 from GMT offset, -36000
seconds.

References:

  • timezone_name_from_abbr
  • date_default_timezone_set
  • date

Convert UTC offset date to different time zone

Your approach is correct. However, I would suggest if possible to work to begin with, with ZonedDateTime or OffsetDateTime. in this case switching between timezones is much easier. For ZonedDateTime switching to different time zone is just one method: public ZonedDateTime withZoneSameInstant(ZoneId zone)

Convert a date with UTC timezone offset to corresponding local timezone format

since your input already contains a UTC offset, you can parse the iso-format string to aware datetime (tzinfo set) and use astimezone to set the correct time zone. Using pytz:

from datetime import datetime
from pytz import timezone # Python 3.9: zoneinfo (standard lib)

str_date = '2020-01-01T00:00:00-08:00'

# to datetime
dt = datetime.fromisoformat(str_date)

# to tz
dt_tz = dt.astimezone(timezone("America/Los_Angeles"))

print(dt_tz)
# 2020-01-01 00:00:00-08:00
print(repr(dt_tz))
# datetime.datetime(2020, 1, 1, 0, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
print(dt_tz.strftime("%a, %d %b %Y %H:%M:%S %Z"))
# Wed, 01 Jan 2020 00:00:00 PST

See also: Display the time in a different time zone - e.g. this answer for a Python 3.9/zoneinfo example.

Convert utc time to timezone time using an offset in minutes C#

To answer your question directly as asked:

public DateTimeOffset GetDateTimeOffsetAtTimezone(int timezoneOffsetInMinutes)
{
// Start out with the current UTC time as a DateTimeOffset
DateTimeOffset utc = DateTimeOffset.UtcNow;

// Get the offset as a TimeSpan
TimeSpan offset = TimeSpan.FromMinutes(timezoneOffsetInMinutes);

// Apply the offset to the UTC time to calculate the resulting DateTimeOffset
DateTimeOffset result = utc.ToOffset(offset);

return result;
}

That said - be sure you are only doing this when you are relaying the current time zone offset - the one that's valid now on the client, and now on the server (a reasonable transmission delay is acceptable). To understand why, refer to to "Time Zone != Offset" in the timezone tag wiki.

If you also need to work with times other than now, then you'll need to instead gather the time zone ID from the client, not the offset.

var timeZoneId = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(timeZoneId);

How to convert UTC + Offset Date to Local?

If 2016-07-28 16:00:00.000 is in UTC, then you need to treat it as such. As ISO8601, it should be 2016-07-28T16:00:00.000Z. You can get this with moment like so:

var i = "2016-07-28 16:00:00.000";
var s = moment.utc(i).toISOString();

Or without moment, like so:

var i = "2016-07-28 16:00:00.000";
var s = new Date(i + " UTC").toISOString(); // yes, a non-standard hack, but works.

This creates the string: "2016-07-28T16:00:00.000Z"

Then when you want to use it on the client side:

var i = "2016-07-28T16:00:00.000Z";
var m = moment(i); // here's a moment object you can use with your picker
var d = m.toDate(); // or, if you want a Date object

// or, if you want to custom format a string
var s = m.format("DD MM YYYY HH:mm:ss");

Or if you want to do this with the Date object alone:

var i = "2016-07-28T16:00:00.000Z";
var d = new Date(i);

(But custom formating is more difficult without moment)

Converting other time zones into local time zone (offset)

You can create a timezone object from the UTC offset hours via a timedelta object. Then use tzlocal to obtain the local time zone (i.e. the one your machine is configured to use) and convert using astimezone.

Ex:

from datetime import datetime, timedelta, timezone
from tzlocal import get_localzone # pip install tzlocal

def to_local(s, offsethours):
"""
convert date/time string plus UTC offset hours to date/time in
local time zone.
"""
dt = datetime.fromisoformat(s).replace(tzinfo=timezone(timedelta(hours=offsethours)))
# for Python < 3.7, use datetime.strptime(s, "%Y-%m-%d %H:%M") instead of datetime.fromisoformat(s)
return dt.astimezone(get_localzone())


time_string = "2021-08-13 19:00"
time_offset = -4

dt_local = to_local(time_string, time_offset)

print(repr(dt_local))
print(dt_local.isoformat())
print(dt_local.utcoffset())
# datetime.datetime(2021, 8, 14, 1, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
# 2021-08-14T01:00:00+02:00
# 2:00:00

Convert UTC date time to local date time

Append 'UTC' to the string before converting it to a date in javascript:

var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"


Related Topics



Leave a reply



Submit