Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Timezone per thread? [closed]

I know we could change the current culture for the current thread. And I know we couldn't get TimeZoneInfo from the CurrentCulture because one culture may has many TimeZones like USA

But to use the same technique to deal with TimeZone for current thread.

It would be very nice if we could make something like this:

TimeZone.CurrentTimeZone = TimeZoneInfo.FindSystemTimeZoneById("timezone id");
like image 629
Wahid Bitar Avatar asked Mar 28 '13 12:03

Wahid Bitar


People also ask

How do I set the timezone in Java?

You can explicitly set a default time zone on the command line by using the Java system property called user. timezone . This bypasses the settings in the Windows operating system and can be a workaround.

How do I change timezone in Intellij?

Under VM options, type the timezone you want. Example: -Duser. timezone="UTC" if you want UTC.


1 Answers

Unfortunately, any concept of the "current" time zone is tied to the operating system settings of the machine that the code is running on. There are some Win32 apis for changing the time zone, but I don't recommend using them. Not only are they not "thread-safe", but they aren't "process-safe" either. The time zone setting affects everything running on the machine.

That said, I'd be curious what your use case really is. If you are in the position to set the timezone per thread, then you are probably in a position to not rely on the local setting at all. You can probably make use of the conversion methods on TimeZoneInfo instead.

For example, say you were looking for the current time in some other time zone. You might be looking for the ability to do this:

using (TimeZone.CurrentTimeZone = ...  )
{
    var now = DateTime.Now;
}

But instead you should simply convert from UTC where appropriate:

var now = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(
                       DateTime.UtcNow, "some other timezone id");
like image 172
Matt Johnson-Pint Avatar answered Oct 27 '22 21:10

Matt Johnson-Pint