Solved

Time zone question

Posted on 2004-08-22
7
624 Views
Last Modified: 2007-12-19
Hello EE community

Can anyone help with this problem.

I have found the code I require on the following page:

http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_20621580.html

The code is:

[StructLayout(LayoutKind.Sequential,Pack=2)]
public struct SYSTEMTIME
{
public short wYear;
public short wMonth;
public short wDayOfWeek;
public short wDay;
public short wHour;
public short wMinute;
public short wSecond;
public short wMilliseconds;
}

// MS KB Q115231
[StructLayout(LayoutKind.Sequential,Pack=2)]
public struct TZI
{
public int Bias;
public int StandardBias;
public int DaylightBias;
public SYSTEMTIME StandardDate;
public SYSTEMTIME DaylightDate;
}

[StructLayout(LayoutKind.Sequential,Pack=2)]
public struct TIME_ZONE_INFORMATION {
   public int Bias;
   [ MarshalAs( UnmanagedType.ByValArray, SizeConst=64)]
   public byte[] StandardName;
   public SYSTEMTIME StandardDate;
   public int    StandardBias;

   [ MarshalAs( UnmanagedType.ByValArray, SizeConst=64)]
   public byte[] DaylightName;
   public SYSTEMTIME DaylightDate;
   public int    DaylightBias;
}

  [DllImport("Kernel32.dll")]
  public static extern int FormatMessage(int flags, IntPtr source, int messageId, int languageId, StringBuilder
   buffer, int size, IntPtr arguments );
 public const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
 
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool SystemTimeToTzSpecificLocalTime(ref TIME_ZONE_INFORMATION lpTimeZoneInformation, ref SYSTEMTIME lpUniversalTime, out SYSTEMTIME lpLocalTime);


public void test() {
RegistryKey rootKey = Registry.LocalMachine;
// only on NT+!
rootKey = rootKey.OpenSubKey( @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\" );
string[] zones = rootKey.GetSubKeyNames();

int year = DateTime.Now.Year;
Type tziType = typeof( TZI );
int tziSize = Marshal.SizeOf( tziType );
foreach( string zone in zones )
{
RegistryKey zoneKey = rootKey.OpenSubKey( zone );
Response.Write( zone + "<BR>");

byte[] bytes = zoneKey.GetValue("TZI") as byte[];
zoneKey.Close();
if( bytes == null )
continue;
if( bytes.Length < tziSize )
continue;

GCHandle handle = GCHandle.Alloc( bytes, GCHandleType.Pinned );
IntPtr buffer = handle.AddrOfPinnedObject();
TZI tzi = (TZI) Marshal.PtrToStructure( buffer, tziType );
handle.Free();

Response.Write( " Bias : "+tzi.Bias.ToString()+"<BR>");
Response.Write( " DaylightBias : "+tzi.DaylightBias.ToString()+"<BR>");

DateTime tzSD = DateTime.Now;
DateTime tzSD2 = DateTime.Now;

if( tzi.DaylightDate.wMonth > 0 )
{

tzSD = new DateTime( year, tzi.DaylightDate.wMonth, tzi.DaylightDate.wDay,
tzi.DaylightDate.wHour, tzi.DaylightDate.wMinute, tzi.DaylightDate.wSecond,
tzi.DaylightDate.wMilliseconds );

tzSD2 = new DateTime( year, tzi.StandardDate.wMonth, tzi.StandardDate.wDay,
tzi.StandardDate.wHour, tzi.StandardDate.wMinute, tzi.StandardDate.wSecond,
tzi.StandardDate.wMilliseconds );

Response.Write( " DaylightDate : "+tzSD.ToString("s")+"<BR>"  );
Response.Write( " StandardDate : "+tzSD2.ToString("s")+"<BR>"  );
}
DateTime x = DateTime.Now.ToUniversalTime();
SYSTEMTIME myTime,localTime;

myTime.wYear = (short)  x.Year;
myTime.wMonth = (short) x.Month;
myTime.wDayOfWeek = (short) x.DayOfWeek;
myTime.wDay = (short)  x.Day;
myTime.wHour = (short) x.Hour;
myTime.wMinute = (short) x.Minute;
myTime.wSecond = (short) x.Second;
myTime.wMilliseconds = (short) x.Millisecond;

localTime.wYear = (short)  x.Year;
localTime.wMonth = (short) x.Month;
localTime.wDayOfWeek = (short) x.DayOfWeek;
localTime.wDay = (short)  x.Day;
localTime.wHour = (short) x.Hour;
localTime.wMinute = (short) x.Minute;
localTime.wSecond = (short) x.Second;
localTime.wMilliseconds = (short) x.Millisecond;

TIME_ZONE_INFORMATION tziTemp;
tziTemp.Bias = tzi.Bias;
tziTemp.StandardBias = tzi.StandardBias;
tziTemp.DaylightBias = tzi.DaylightBias;
tziTemp.StandardDate=tzi.StandardDate;
tziTemp.DaylightDate=tzi.DaylightDate;
tziTemp.StandardName = new byte[64];
tziTemp.DaylightName = new byte[64];

SystemTimeToTzSpecificLocalTime(ref tziTemp, ref myTime, out localTime);

//Response.Write(localTime.wDay + "<BR>");
DateTime localDateTime = new DateTime( localTime.wYear, localTime.wMonth, localTime.wDay,
localTime.wHour, localTime.wMinute, localTime.wSecond,localTime.wMilliseconds );

Response.Write("Local time = "+localDateTime+"<BR>");


********************************
********************************
********************************

Could someone tell me how I can add the code to my page .
i.e
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script language="C#" runat="server">
void Page_Load(object sender, System.EventArgs e)
{
 
}
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
</body>
</html>

Thank You
Caz


0
Comment
Question by:BeginningWebDesign
  • 3
  • 3
7 Comments
 
LVL 1

Expert Comment

by:hammadraza
ID: 11867464
you should add this code to your "code behind" file rather than ASPX file.
0
 
LVL 10

Expert Comment

by:123654789987
ID: 11868099
You can create a function in your CodeBehind and add the logic there. Then you can call this function during Page_Load either from codebehind or using script language.
0
 

Author Comment

by:BeginningWebDesign
ID: 11868438
Hi
Could anyone do the above for me, as i'm not sure how to.

Caz
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 1

Expert Comment

by:hammadraza
ID: 11868567
What do you want the code should return you?
0
 
LVL 1

Accepted Solution

by:
hammadraza earned 500 total points
ID: 11868728
Ok Here is complete code for the application just copy and paste it in your code behind file. But beware to remove any other code persent in code behind file before pasting this one.


------------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Runtime.InteropServices;
using Microsoft.Win32;

namespace TestApp
{
      /// <summary>
      /// Summary description for WebForm1.
      /// </summary>
      public class WebForm1 : System.Web.UI.Page
      {
                        private void Page_Load(object sender, System.EventArgs e)
                        {
                              // Put user code to initialize the page here
                              test();
                        }

            
            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.Load += new System.EventHandler(this.Page_Load);
            }
            #endregion
      
            [StructLayout(LayoutKind.Sequential,Pack=2)]
                  public struct SYSTEMTIME
            {
                  public short wYear;
                  public short wMonth;
                  public short wDayOfWeek;
                  public short wDay;
                  public short wHour;
                  public short wMinute;
                  public short wSecond;
                  public short wMilliseconds;
            }

            // MS KB Q115231
            [StructLayout(LayoutKind.Sequential,Pack=2)]
                  public struct TZI
            {
                  public int Bias;
                  public int StandardBias;
                  public int DaylightBias;
                  public SYSTEMTIME StandardDate;
                  public SYSTEMTIME DaylightDate;
            }

            [StructLayout(LayoutKind.Sequential,Pack=2)]
                  public struct TIME_ZONE_INFORMATION
            {
                  public int Bias;
                  [ MarshalAs( UnmanagedType.ByValArray, SizeConst=64)]
                  public byte[] StandardName;
                  public SYSTEMTIME StandardDate;
                  public int    StandardBias;

                  [ MarshalAs( UnmanagedType.ByValArray, SizeConst=64)]
                  public byte[] DaylightName;
                  public SYSTEMTIME DaylightDate;
                  public int    DaylightBias;
            }

            [DllImport("Kernel32.dll")]
            public static extern int FormatMessage(int flags, IntPtr source, int messageId, int languageId, string buffer, int size, IntPtr arguments );
            public const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
 
            [DllImport("kernel32.dll", SetLastError=true)]
            public static extern bool SystemTimeToTzSpecificLocalTime(ref TIME_ZONE_INFORMATION lpTimeZoneInformation, ref SYSTEMTIME lpUniversalTime, out SYSTEMTIME lpLocalTime);


            public void test()
            {
                  RegistryKey rootKey = Registry.LocalMachine;
                  // only on NT+!
                  rootKey = rootKey.OpenSubKey( @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\" );
                  string[] zones = rootKey.GetSubKeyNames();

                  int year = DateTime.Now.Year;
                  Type tziType = typeof( TZI );
                  int tziSize = Marshal.SizeOf( tziType );
                  foreach( string zone in zones )
                  {
                        RegistryKey zoneKey = rootKey.OpenSubKey( zone );
                        Response.Write( zone + "<BR>");

                        byte[] bytes = zoneKey.GetValue("TZI") as byte[];
                        zoneKey.Close();
                        if( bytes == null )
                              continue;
                        if( bytes.Length < tziSize )
                              continue;

                        GCHandle handle = GCHandle.Alloc( bytes, GCHandleType.Pinned );
                        IntPtr buffer = handle.AddrOfPinnedObject();
                        TZI tzi = (TZI) Marshal.PtrToStructure( buffer, tziType );
                        handle.Free();

                        Response.Write( " Bias : "+tzi.Bias.ToString()+"<BR>");
                        Response.Write( " DaylightBias : "+tzi.DaylightBias.ToString()+"<BR>");

                        DateTime tzSD = DateTime.Now;
                        DateTime tzSD2 = DateTime.Now;

                        if( tzi.DaylightDate.wMonth > 0 )
                        {

                              tzSD = new DateTime( year, tzi.DaylightDate.wMonth, tzi.DaylightDate.wDay,
                                    tzi.DaylightDate.wHour, tzi.DaylightDate.wMinute, tzi.DaylightDate.wSecond,
                                    tzi.DaylightDate.wMilliseconds );

                              tzSD2 = new DateTime( year, tzi.StandardDate.wMonth, tzi.StandardDate.wDay,
                                    tzi.StandardDate.wHour, tzi.StandardDate.wMinute, tzi.StandardDate.wSecond,
                                    tzi.StandardDate.wMilliseconds );

                              Response.Write( " DaylightDate : "+tzSD.ToString("s")+"<BR>"  );
                              Response.Write( " StandardDate : "+tzSD2.ToString("s")+"<BR>"  );
                        }
                        DateTime x = DateTime.Now.ToUniversalTime();
                        SYSTEMTIME myTime,localTime;

                        myTime.wYear = (short)  x.Year;
                        myTime.wMonth = (short) x.Month;
                        myTime.wDayOfWeek = (short) x.DayOfWeek;
                        myTime.wDay = (short)  x.Day;
                        myTime.wHour = (short) x.Hour;
                        myTime.wMinute = (short) x.Minute;
                        myTime.wSecond = (short) x.Second;
                        myTime.wMilliseconds = (short) x.Millisecond;

                        localTime.wYear = (short)  x.Year;
                        localTime.wMonth = (short) x.Month;
                        localTime.wDayOfWeek = (short) x.DayOfWeek;
                        localTime.wDay = (short)  x.Day;
                        localTime.wHour = (short) x.Hour;
                        localTime.wMinute = (short) x.Minute;
                        localTime.wSecond = (short) x.Second;
                        localTime.wMilliseconds = (short) x.Millisecond;

                        TIME_ZONE_INFORMATION tziTemp;
                        tziTemp.Bias = tzi.Bias;
                        tziTemp.StandardBias = tzi.StandardBias;
                        tziTemp.DaylightBias = tzi.DaylightBias;
                        tziTemp.StandardDate=tzi.StandardDate;
                        tziTemp.DaylightDate=tzi.DaylightDate;
                        tziTemp.StandardName = new byte[64];
                        tziTemp.DaylightName = new byte[64];

                        SystemTimeToTzSpecificLocalTime(ref tziTemp, ref myTime, out localTime);

                        //Response.Write(localTime.wDay + "<BR>");
                        DateTime localDateTime = new DateTime( localTime.wYear, localTime.wMonth, localTime.wDay,
                              localTime.wHour, localTime.wMinute, localTime.wSecond,localTime.wMilliseconds );

                        Response.Write("Local time = "+localDateTime+"<BR>");
                  }
            }
      }
}

------------------------------------------------------------------------------------------------

0
 

Author Comment

by:BeginningWebDesign
ID: 11868825
Hi hammadraza

Idealy I would want the code to return the day and time, I have being looking at various other websites and think that the above code may cause a problem due to countries daylight saving times.

Is it posssible to change the question to the one below.

I live in the UK and the website I'm designing is also located in the UK.
Therfore is it possible to do the following.

1) Take the current date and time from my computer.
2) Take away the UK daylight saving times.
This changes every year, this year it is between: Sundays of 28 March and 31 October
2) Add the GMT time for example Athens +3 hrs
3) Display the Time as: Monday, August 23, 2004, at 12:59:44 PM

I think code would be  something like:

CurrentDateTime = DateTime();//Get current time
RemoveDLS = DateTime; //Remove daylight saving time
DisplayTime;//Display time
if(CurrentDateTime > 28/03/2004 02:00 && CurrentDateTime < 31/10/2004 02:00)
{
RemoveDLS = -1
}
else
{
RemoveDLS = 0
}
DisplayTime.Text = RemoveDLS +3.ToString(T)


I would then have in the page:
 Current time in Athens <asp:label id="DisplayTime" runat="server"/> GMT<br>
Daylight savings is not taking into account Add 1 hour to time

i.e time would be: Monday, August 23, 2004 12:59

Hope you can understand that.
Caz



0
 

Author Comment

by:BeginningWebDesign
ID: 11868840
Hi hammadraza

Sorry had not realised you had answered question.

Caz
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now