Convert Utc Datetime to Another Time Zone

Convert UTC DateTime to another Time Zone

Have a look at the DateTimeOffset structure:

// user-specified time zone
TimeZoneInfo southPole =
TimeZoneInfo.FindSystemTimeZoneById("Antarctica/South Pole Standard Time");

// an UTC DateTime
DateTime utcTime = new DateTime(2007, 07, 12, 06, 32, 00, DateTimeKind.Utc);

// DateTime with offset
DateTimeOffset dateAndOffset =
new DateTimeOffset(utcTime, southPole.GetUtcOffset(utcTime));

Console.WriteLine(dateAndOffset);

For DST see the TimeZoneInfo.IsDaylightSavingTime method.

bool isDst = southpole.IsDaylightSavingTime(DateTime.UtcNow);

How to convert a UTC datetime to a local datetime using only standard library?

I think I figured it out: computes number of seconds since epoch, then converts to a local timzeone using time.localtime, and then converts the time struct back into a datetime...

EPOCH_DATETIME = datetime.datetime(1970,1,1)
SECONDS_PER_DAY = 24*60*60

def utc_to_local_datetime( utc_datetime ):
delta = utc_datetime - EPOCH_DATETIME
utc_epoch = SECONDS_PER_DAY * delta.days + delta.seconds
time_struct = time.localtime( utc_epoch )
dt_args = time_struct[:6] + (delta.microseconds,)
return datetime.datetime( *dt_args )

It applies the summer/winter DST correctly:

>>> utc_to_local_datetime( datetime.datetime(2010, 6, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 6, 6, 19, 29, 7, 730000)
>>> utc_to_local_datetime( datetime.datetime(2010, 12, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 12, 6, 18, 29, 7, 730000)

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)"

How to convert UTC datetime to another timezone?

Use DateTime and DateTimeZone.

$date = new DateTime('2012-07-16 01:00:00 +00');
$date->setTimezone(new DateTimeZone('Europe/Moscow')); // +04

echo $date->format('Y-m-d H:i:s'); // 2012-07-15 05:00:00

Convert UTC datetime string to local datetime

If you don't want to provide your own tzinfo objects, check out the python-dateutil library. It provides tzinfo implementations on top of a zoneinfo (Olson) database such that you can refer to time zone rules by a somewhat canonical name.

from datetime import datetime
from dateutil import tz

# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')

# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
central = utc.astimezone(to_zone)

Edit Expanded example to show strptime usage

Edit 2 Fixed API usage to show better entry point method

Edit 3 Included auto-detect methods for timezones (Yarin)

Convert date to another timezone in JavaScript

Here is the one-liner:

function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}

// usage: Asia/Jakarta is GMT+7
convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time)

// Resulting value is regular Date() object
const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta")
convertedDate.getHours(); // 17

// Bonus: You can also put Date object to first arg
const date = new Date()
convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.

How to convert an UTC datetime to a specified Time zone?

A few things:

  • "Antarctica/South Pole Standard Time" isn't a real time zone identifier. I assume you gave that in jest, but it makes it unclear as to whether you want to use Windows time zone identifiers (like "Eastern Standard Time"), or IANA time zone identifiers (like "America/New_York").

  • Assuming you want to use Windows identifiers, you can indeed use the functions in the Win32 API. The comment in the question suggested the wrong API however. You should instead use SystemTimeToTzSpecificLocalTimeEx.

    • It uses the DYNAMIC_TIME_ZONE_INFORMATION structure, which have been available since Windows Vista. To get one of those from a named Windows time zone identifier, use the EnumDynamicTimeZoneInformation function to loop through the system time zones until you find the one matching on the TimeZoneKeyName field.
    • The "dynamic" structures are important to use, and should always be preferred over their older counterparts. They allow access to changes in time zones and daylight saving time rules that are stored in the Windows registry. Without them, you only get access to the current rule, which might not be the correct rule for the date you are converting.
  • If you instead wanted to use IANA time zone identifiers, use the Delphi tzdb library, as shown in this post.

    • If you are uncertain of which to use, I highly recommend this approach. IANA identifiers are inter-operable with other operating systems, programming languages, frameworks, and libraries. (Windows identifiers, less so.)


Related Topics



Leave a reply



Submit