How to Convert Utc Datetime to Another Timezone

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

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)

Trying to convert UTC time with specific time zones

You can create a date for the sunrise by adding the timezone value.

The example below will produce a date and time in the timezone of the weather record (Horinouchi), NOT the timezone of the user.

const data = {
"dt": 1609176171,
"sys": {
"type": 1,
"id": 8074,
"country": "JP",
"sunrise": 1609192224,
"sunset": 1609227369
},
"timezone": 32400,
"id": 1862143,
"name": "Horinouchi",
"cod": 200
};

// extract sunrise and timezone offset in UNIX epoch seconds
const {
sys: {sunrise},
timezone
} = data;

// create Date object for sunrise with timezone offset
const srTime = new Date((sunrise+timezone)*1000);

// convert number to a 2-digit string
const twoDigits = (val) => {
return ('0' + val).slice(-2);
};

const year = srTime.getUTCFullYear();
const month = twoDigits(srTime.getUTCMonth()+1);
const dayOfMonth = twoDigits(srTime.getUTCDate());
const hours = twoDigits(srTime.getUTCHours());
const minutes = twoDigits(srTime.getUTCMinutes());
const seconds = twoDigits(srTime.getUTCSeconds());

console.log(`${year}-${month}-${dayOfMonth} ${hours}:${minutes}:${seconds}`);

convert date and time in any timezone to UTC zone

You cannot "convert that date values" to other timezones or UTC. The type java.util.Date does not have any internal timezone state and only refers to UTC by spec in a way which cannot be changed by user (just counting the milliseconds since UNIX epoch in UTC timezone leaving aside leapseconds).

But you can convert the formatted String-representation of a java.util.Date to another timezone. I prefer to use two different formatters, one per timezone (and pattern). I also prefer to use "Asia/Kolkata" in your case because then it will universally works (IST could also be "Israel Standard Time" which will be interpreted differently in Israel):

DateFormat formatterIST = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterIST.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); // better than using IST
Date date = formatterIST.parse("15-05-2014 00:00:00");
System.out.println(formatterIST.format(date)); // output: 15-05-2014 00:00:00

DateFormat formatterUTC = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterUTC.setTimeZone(TimeZone.getTimeZone("UTC")); // UTC timezone
System.out.println(formatterUTC.format(date)); // output: 14-05-2014 18:30:00

// output in system timezone using pattern "EEE MMM dd HH:mm:ss zzz yyyy"
System.out.println(date.toString()); // output in my timezone: Wed May 14 20:30:00 CEST 2014

How to convert local time string to UTC?

Thanks @rofly, the full conversion from string to string is as follows:

import time
time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00",
"%Y-%m-%d %H:%M:%S"))))

My summary of the time/calendar functions:

time.strptime

string --> tuple (no timezone applied, so matches string)

time.mktime

local time tuple --> seconds since epoch (always local time)

time.gmtime

seconds since epoch --> tuple in UTC

and

calendar.timegm

tuple in UTC --> seconds since epoch

time.localtime

seconds since epoch --> tuple in local timezone

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)

Converting UTC dates to other timezones

It turns out the code was almost correct, what I didn't take into account was that when parsing the String to get a Date object initially, it uses default system TimeZone, so the source date was not in UTC as I expected.

The trick was to set the timezone when parsing the date to UTC and then set it to destination TimeZone. Something like this:

SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsed = sourceFormat.parse("2011-03-01 15:10:37"); // => Date is in UTC now

TimeZone tz = TimeZone.getTimeZone("America/Chicago");
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
destFormat.setTimeZone(tz);

String result = destFormat.format(parsed);


Related Topics



Leave a reply



Submit