473,785 Members | 2,878 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get Current Time in Different Timezone

Hello:

I would like it so that the time displayed was always for CDT/CDS.
Potentially, the application can be run at locations in Mountain Time
or Central Time. This is what I have now:

// get the UTC offset depending on day light savings
double hourOffset = DateTime.Now.Is DaylightSavingT ime() ? -5 : -6;
DateTimeOffset offset =
DateTimeOffset. UtcNow.ToOffset (TimeSpan.FromH ours(hourOffset ));

Essentially, is there a way to get the time in a particular timezone
regardless of where the application is run?

Thanks,
Travis
Feb 12 '08 #1
6 20326
On 12 Feb, 18:34, "jehugalea...@g mail.com" <jehugalea...@g mail.com>
wrote:
Hello:

I would like it so that the time displayed was always for CDT/CDS.
Potentially, the application can be run at locations in Mountain Time
or Central Time. This is what I have now:

*// get the UTC offset depending on day light savings
double hourOffset = DateTime.Now.Is DaylightSavingT ime() ? -5 : -6;
DateTimeOffset offset =
DateTimeOffset. UtcNow.ToOffset (TimeSpan.FromH ours(hourOffset ));

Essentially, is there a way to get the time in a particular timezone
regardless of where the application is run?

Thanks,
Travis
I think u need to know where u are,,, and using that knowledge and
accepting that NTP has corrected your clock, dont worry.
OR With user interaction I think that can be a possibility - as in the
user sets the clock right. Without, a GPS would be advisable.
Never heard of mountain time, greenwitch OK but...nah...

//CY
Feb 12 '08 #2
On Feb 12, 10:57*am, christ...@gmail .com wrote:
On 12 Feb, 18:34, "jehugalea...@g mail.com" <jehugalea...@g mail.com>
wrote:


Hello:
I would like it so that the time displayed was always for CDT/CDS.
Potentially, the application can be run at locations in Mountain Time
or Central Time. This is what I have now:
*// get the UTC offset depending on day light savings
double hourOffset = DateTime.Now.Is DaylightSavingT ime() ? -5 : -6;
DateTimeOffset offset =
DateTimeOffset. UtcNow.ToOffset (TimeSpan.FromH ours(hourOffset ));
Essentially, is there a way to get the time in a particular timezone
regardless of where the application is run?
Thanks,
Travis

I think u need to know where u are,,, and using that knowledge and
accepting that NTP has corrected your clock, dont worry.
OR With user interaction I think that can be a possibility - as in the
user sets the clock right. Without, a GPS would be advisable.
Never heard of mountain time, greenwitch OK but...nah...

//CY- Hide quoted text -

- Show quoted text -
Mountain time? Between Central and Pacific? Anyway, human intervention
is not possible.
Feb 12 '08 #3
On Tue, 12 Feb 2008 09:34:50 -0800, je**********@gm ail.com
<je**********@g mail.comwrote:
I would like it so that the time displayed was always for CDT/CDS.
Potentially, the application can be run at locations in Mountain Time
or Central Time. This is what I have now:

// get the UTC offset depending on day light savings
double hourOffset = DateTime.Now.Is DaylightSavingT ime() ? -5 : -6;
DateTimeOffset offset =
DateTimeOffset. UtcNow.ToOffset (TimeSpan.FromH ours(hourOffset ));

Essentially, is there a way to get the time in a particular timezone
regardless of where the application is run?
There's always a way. :)

However, .NET does not, AFAIK, support this directly. It only knows two
timezones: UTC, and your current local timezone. The API actually _looks_
like it could support multiple timezones, if only there were a way to
instantiate a new timezone object according to something other than the
local settings, but I haven't seen anything like that yet.

So you're stuck doing this manually for now. I would hope that in the
future, .NET will include more broad support for timezones, but that
future isn't here yet as far as I know.

By the way, beware of the use of "IsDaylightSavi ngTime" when creating
DateTime instances outside the local timezone. It will be relative to the
local timezone, which of course may have different daylight saving time
rules than the target timezone.

Pete
Feb 12 '08 #4
On Feb 12, 12:06*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Tue, 12 Feb 2008 09:34:50 -0800, jehugalea...@gm ail.com *

<jehugalea...@g mail.comwrote:
I would like it so that the time displayed was always for CDT/CDS.
Potentially, the application can be run at locations in Mountain Time
or Central Time. This is what I have now:
*// get the UTC offset depending on day light savings
double hourOffset = DateTime.Now.Is DaylightSavingT ime() ? -5 : -6;
DateTimeOffset offset =
DateTimeOffset. UtcNow.ToOffset (TimeSpan.FromH ours(hourOffset ));
Essentially, is there a way to get the time in a particular timezone
regardless of where the application is run?

There's always a way. *:)

However, .NET does not, AFAIK, support this directly. *It only knows two*
timezones: UTC, and your current local timezone. *The API actually _looks_ *
like it could support multiple timezones, if only there were a way to *
instantiate a new timezone object according to something other than the *
local settings, but I haven't seen anything like that yet.

So you're stuck doing this manually for now. *I would hope that in the *
future, .NET will include more broad support for timezones, but that *
future isn't here yet as far as I know.
That stinks. I was reading a post somewhere else where they were using
the registry to get all available Timezones. However, I am not sure
how they figured out UTC offsets from that, nor how they handled Day
Light Savings Time. I will just ignore it.
>
By the way, beware of the use of "IsDaylightSavi ngTime" when creating *
DateTime instances outside the local timezone. *It will be relative to the *
local timezone, which of course may have different daylight saving time *
rules than the target timezone.
Right. This was my biggest problem with my code. I am going to let it
slide for now, since I can guarantee that the program will be in
Mountain or Central time when run. I don't have to worry about there
being alternate timezone rules within the US, I hope!
>
Pete
Feb 12 '08 #5
je**********@gm ail.com wrote:
On Feb 12, 12:21 pm, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
>Peter Duniho <NpOeStPe...@nn owslpianmk.comw rote:
>>However, .NET does not, AFAIK, support this directly. It only knows two
timezones: UTC, and your current local timezone. The API actually _looks_
like it could support multiple timezones, if only there were a way to
instantiate a new timezone object according to something other than the
local settings, but I haven't seen anything like that yet.
Fortunately it's available as of .NET 3.5.

See DateTimeOffset (available in .NET 2.0 SP1) and TimeZoneInfo (3.5).

I was reading about that in my Nutshell book. How great it would be to
live in a 3.5 world!
Someone asked about timezone a couple of months ago.

I came up with the following two potential solutions:

public static int GetUTCOffset1(s tring target)
{
RegistryKey tzs =
Registry.LocalM achine.OpenSubK ey("SOFTWARE"). OpenSubKey("Mic rosoft").OpenSu bKey("Windows
NT").OpenSubKey ("CurrentVersio n").OpenSubKey( "Time Zones");
foreach(string tzn in tzs.GetSubKeyNa mes())
{
if(tzn.Contains (target) ||

((string)tzs.Op enSubKey(tzn).G etValue("Displa y")).Contains(t arget))
{
return
-BitConverter.To Int32((byte[])(tzs.OpenSubKe y(tzn).GetValue ("TZI")), 0);
}
}
throw new ArgumentExcepti on("Unknown timezone " + target);
}
public static int GetUTCOffset2(s tring target)
{
java.util.TimeZ one tz = java.util.TimeZ one.getTimeZone (target);
return tz.getRawOffset () / 60000;
}

Arne
Feb 13 '08 #6

"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
On Tue, 12 Feb 2008 11:23:05 -0800, je**********@gm ail.com
<je**********@g mail.comwrote:
>[...]
That stinks. I was reading a post somewhere else where they were using
the registry to get all available Timezones. However, I am not sure
how they figured out UTC offsets from that, nor how they handled Day
Light Savings Time. I will just ignore it.

I don't recall the format off the top of my head, but the timezone
database in the registry is not all that complicated. Microsoft has a KB
article on their support web site...
You'll find that KB article here:
http://support.microsoft.com/kb/115231

Once you're grabbed all the timezones from the registry you can use
SystemTimeToTzS pecificLocalTim e and
TzSpecificLocal TimeToSystemTim e to convert betwen UTC and timezone specific
local time

The following code should help:

[DllImport("kern el32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
private static extern int SystemTimeToTzS pecificLocalTim e(ref
TIME_ZONE_INFOR MATION lpTimeZone, ref SYSTEMTIME lpUniversalTIme , out
SYSTEMTIME lpLocalTime);

[DllImport("kern el32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
private static extern int TzSpecificLocal TimeToSystemTim e(ref
TIME_ZONE_INFOR MATION lpTimeZone, ref SYSTEMTIME lpLocalTime, out SYSTEMTIME
lpUniversalTIme );

[StructLayout(La youtKind.Sequen tial)]
private struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}

//Registry time zone format. See KB article Q115231
[StructLayout(La youtKind.Sequen tial)]
private struct REG_TIME_ZONE_I NFORMATION
{
public int Bias;
public int StandardBias;
public int DaylightBias;
public SYSTEMTIME StandardDate;
public SYSTEMTIME DaylightDate;
}

[StructLayout(La youtKind.Sequen tial, CharSet = CharSet.Unicode )]
private struct TIME_ZONE_INFOR MATION
{
public int Bias;
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 32)]
public string StandardName;
public SYSTEMTIME StandardDate;
public int StandardBias;
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 32)]
public string DaylightName;
public SYSTEMTIME DaylightDate;
public int DaylightBias;
}

private static List<TIME_ZONE_ INFORMATIONGetT imeZones()
{
List<TIME_ZONE_ INFORMATIONlist = new List<TIME_ZONE_ INFORMATION>();
RegistryKey key =
Registry.LocalM achine.OpenSubK ey(@"SOFTWARE\M icrosoft\Window s
NT\CurrentVersi on\Time Zones");
if (key == null)
return list;

string[] subKeyNames = key.GetSubKeyNa mes();
foreach (string subKeyName in subKeyNames)
{
RegistryKey subKey = key.OpenSubKey( subKeyName);
if (subKey != null)
{
object value = subKey.GetValue ("TZI");
if (value != null)
{
int length =
Marshal.SizeOf( typeof(REG_TIME _ZONE_INFORMATI ON));
IntPtr p = Marshal.AllocHG lobal(length);
Marshal.Copy((b yte[])value, 0, p, length);
REG_TIME_ZONE_I NFORMATION rtzi =
(REG_TIME_ZONE_ INFORMATION)Mar shal.PtrToStruc ture(p,
typeof(REG_TIME _ZONE_INFORMATI ON));
Marshal.FreeHGl obal(p);

TIME_ZONE_INFOR MATION tzi = new TIME_ZONE_INFOR MATION();
tzi.Bias = rtzi.Bias;
tzi.DaylightBia s = rtzi.DaylightBi as;
tzi.StandardBia s = rtzi.StandardBi as;
tzi.DaylightDat e = rtzi.DaylightDa te;
tzi.StandardDat e = rtzi.StandardDa te;
tzi.DaylightNam e = (string)subKey. GetValue("Dlt", "");
tzi.StandardNam e = (string)subKey. GetValue("Std", "");
list.Add(tzi);
}
subKey.Close();
}
}
key.Close();
return list;
}
/claes
Feb 14 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2554
by: Raj Chudasama | last post by:
I have the following code for a clock in my gui. Everything works fine EXCEPT the following line when the TimeZone is changed in the windows. string tz = TimeZone.CurrentTimeZone.StandardName; It will not pick the changed timezone but it does pick up time change due to timezone change.
10
15476
by: David Garamond | last post by:
The Postgres manual says: The AT TIME ZONE construct allows conversions of time stamps to different time zones. I'd guess most people would think what's meant here is something like "unit conversion", and that the timestamp value stays the same (much like 2 feet becomes 24 inches when it's being "converted"). But: # SELECT NOW() = NOW() AT TIME ZONE 'UTC';
7
2683
by: Dick | last post by:
I have a long list of events. I know where each event took place (globally) and when (using the event’s local time). I want to do some comparisons between these date/times. I thought I would convert them all to UTC and thus get them all on a common time-line. But I can’t see how to do this. I can use TimeZone.CurrentTimeZone to get the current TimeZone object and use its ToUniversalTime method to convert dates that occurred in the...
0
1895
by: Saloni | last post by:
I have windows service which is going to run on several machines which are in different time zones in USA. I want to find out the Eastern Zone current time from these different machines. It should return me correct time based on timezone(GMT-4 for DST duration/GMT-5 for non DST duration) Is there any simplest way to do this. Logic which i used is as below: 1.Find Current local time 2.Find GMT time
1
14600
by: davelist | last post by:
I'm guessing there is an easy way to do this but I keep going around in circles in the documentation. I have a time stamp that looks like this (corresponding to UTC time): start_time = '2007-03-13T15:00:00Z' I want to convert it to my local time. start_time = time.mktime(time.strptime(start_time, '%Y-%m-%dT%H:%M:
4
4405
by: Polaris431 | last post by:
I have a web application in ASP.NET that will be used globally. Data is collected on mobile devices running Windows Mobile and sent to the web server where it is stored and can be viewed. Data is timestamped when it is sent from a PDA device to the server. I am writing software for both the web app and the PDA. The web server is located at one location while the PDA devices are located around the world. The question is, how do I handle...
7
2735
by: Correia | last post by:
I have a webserver that is in another country and have a different time zone. How can i fix this and use the scripts with the correct time zone? Thanks
0
1367
by: Pradnyesh Sawant | last post by:
Hello, can someone please tell me how can I programatically detect the timezone information that has been set through kde? basically, I have a small pyqt4 app which shows the current time. however it shows me my system time (dunno where that is stored; basically it shows me time in IST). however, I'm right now in hk and would like the app to show me time in my current timezone (hong kong). Any guidelines how may I go about doing this?
7
9203
by: Damir | last post by:
I have a situation on a DB server where the "current timestamp" command shows the actual system time offset by one hour, which has never been noticed before?!? The DB2 is V9.1 (FP03), running on AIX 5.3. System timezone is offset by one hour to GMT, but this shouldn't cause such behavior. # echo $TZ NFT-1DFT,M3.5.0,M10.5.0
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10329
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8974
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3650
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2880
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.