How to Convert Datetime in Specific Timezone

How to convert DateTime in Specific timezone?

The .NET framework already has classes and methods available to convert DateTimes between different time zones. Have a look at the ConvertTime methods of the TimeZoneInfo class.

Edit: When you get the time to put into the database, assuming it was created with correct time zone information you can easily convert to UTC:

DateTime utcTime = inputDateTime.ToUniversalTime();

Get timeInfo as done in the question edit:

TimeZoneInfo timeInfo = TimeZoneInfo.FindSystemTimeZoneById(GetFromConfig.ManilaTimeZoneKey());

When you send the database time to user, convert it to the correct timezone using timeInfo.

DateTime userTime = TimeZoneInfo.ConvertTimeFromUtc(dbDateTime, timeInfo);

Personally I'd try and keep this logic separate from the propery get/set methods.

Create DateTime in specific time zone then convert to utc

You'd basically need TimeZoneInfo.ConvertTimeToUtc method.

Just make sure the Kind property of the passed DateTime is Unspecified, otherwise the method has special expectations for the sourceTimeZone argument and will throw exception.

e.g.

var testTime = new DateTime(testDate.Year, testDate.Month, testDate.Day, 4, 0, 0);
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("West Asia Standard Time");
var utcTime = TimeZoneInfo.ConvertTimeToUtc(testTime, timeZoneInfo);;

Retrieve date and convert it to specific time zone according to user time zone

$date = new DateTime($result->s_start, new DateTimeZone($result->s_timezone));
$date->setTimezone(new DateTimeZone('Africa/Cairo'));
echo $date->format('Y-m-d H:i:sP') ;

Resources

  • DateTime class
  • DateTimeZone class

Edit A function in the controller to convert timezones.

public function _convert_time($result){
$date = new DateTime($result->s_start, new DateTimeZone($result->s_timezone));
$date->setTimezone(new DateTimeZone('Africa/Cairo'));
return $date->format('Y-m-d H:i:sP') ;
}

Now you can echo the result

foreach($results as $result){
echo $this->_convert_time($result);
}

How do you convert a datetime/timestamp from one timezone to another timezone?

If you know your origin timezone and the new timezone that you want to convert it to, it turns out to be very straightforward:

  1. Make two pytz.timezone objects, one for the current timezone and one for the new timezone e.g. pytz.timezone("US/Pacific"). You can find a list of all official timezones in pytz library: import pytz; pytz.all_timezones

  2. Localize the datetime/timestamp of interest to the current timezone e.g.

current_timezone = pytz.timezone("US/Eastern")
localized_timestamp = current_timezone.localize(timestamp)

  1. Convert to new timezone using .astimezone() on the newly localized datetime/timestamp from step 2 with the desired timezone's pytz object as input e.g. localized_timestamp.astimezone(new_timezone).

Done!

As a full example:

import datetime
import pytz

# a timestamp I'd like to convert
my_timestamp = datetime.datetime.now()

# create both timezone objects
old_timezone = pytz.timezone("US/Eastern")
new_timezone = pytz.timezone("US/Pacific")

# two-step process
localized_timestamp = old_timezone.localize(my_timestamp)
new_timezone_timestamp = localized_timestamp.astimezone(new_timezone)

# or alternatively, as an one-liner
new_timezone_timestamp = old_timezone.localize(my_timestamp).astimezone(new_timezone)

Bonus: but if all you need is the current time in a specific timezone, you can conveniently pass that timezone directly into datetime.now() to get the current times directly:

datetime.datetime.now(new_timezone)

When it comes to needing timezones conversions generally, I would strongly advise that one should store all timestamps in your database in UTC, which has no daylight savings time (DST) transition. And as a good practice, one should always choose to enable time zone support (even if your users are all in a single time zone!). This will help you avoid the DST transition problem that plagues so much software today.

Beyond DST, time in software can be generally quite tricky. To get a sense of just how difficult it is to deal with time in software in general, here is a potentially enlightening resource: http://yourcalendricalfallacyis.com

Even a seemingly simple operation as converting a datetime/timestamp into a date can become non-obvious. As this helpful documentation points out:

A datetime represents a point in time. It’s absolute: it doesn’t depend on anything. On the contrary, a date is a calendaring concept. It’s a period of time whose bounds depend on the time zone in which the date is considered. As you can see, these two concepts are fundamentally different.

Understanding this difference is a key step towards avoiding time-based bugs. Good luck.

Convert Date/Time for given Timezone - java

For me, the simplest way to do that is:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));

//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));

Java Date Time conversion to given timezone

with the help of @ole v.v's explanation i have separated the datetime value for two
1. time
2. timezone

then i used this coding to extract the datetime which is related to the given timezone

//convert datetime to give timezone 
private static String DateTimeConverter (String timeVal, String timeZone)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

SimpleDateFormat offsetDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

offsetDateFormat2.setTimeZone(TimeZone.getTimeZone(timeZone));
String result =null;
try {
result = offsetDateFormat2.format(format.parse(timeVal));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return result;
}


Related Topics



Leave a reply



Submit