Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Time zone question

Posted on 2004-08-22
7
Medium Priority
?
635 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses

704 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