How to set SystemTime in Windows Mobile using C#

No.of Views1901
Bookmarked0 times
Downloads 
Votes0
By  RRaveen   On  09 Dec 2010 03:12:11
Tag : .NET CF , DateTime Controls
In this snippet, I will explain how to set system time pocket pc emulator or device using real world time server to using C#.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this snippet, I will explain how to set system time pocket pc emulator or device using real world time server to using C#.Sometimes you may be need to set real time to device,on that time you have to connect to external website or timer providers using GPRS and get the time from the server and then set to device.

Implementation

There are two part of this implementation, first i will create class for read the time time from live server and set time in pocket pc.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Net;
using System.IO;
using System.Xml;
using System.Globalization;

namespace TimeManager
{
   internal class TimeUtils
    {
        #region ' P/Invoke Method signtures.'
        [DllImport("coredll.dll", SetLastError = true)]
        private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);

        public 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;
        }

        #endregion

        #region ' Public Methods '

        #region // Set System local time from the Server time.
        public static bool SetLocalTime(string RequestURL)
        {
            try
            {
                double dTimeSecond = 0.0;
                // Convert Timestamp to Time
                DateTime oDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                TimeSyncService.TimeSyncService oTimeSyncService = new NetworkManager.TimeSyncService.TimeSyncService();
                RequestURL = string.Concat(RequestURL, "timesyncservice.asmx");
                oTimeSyncService.Url = RequestURL;
                dTimeSecond = oTimeSyncService.GetCurrentTime();
                if (dTimeSecond == 0.0)
                {
                    return false;
                }
                // Get current TimeZone
                TimeZone oCurrentTimeZone = TimeZone.CurrentTimeZone;

                //dTimeSecond = dTimeSecond - (4.5 * 60 * 60);
                oDateTime = oDateTime.AddSeconds(dTimeSecond);
                // Check IsDayLightTime
                if (oCurrentTimeZone.IsDaylightSavingTime(oDateTime))
                {
                    DaylightTime daylightTime = oCurrentTimeZone.GetDaylightChanges(oDateTime.Year);
                    // Here we want to put more work.
                }
                TimeSpan oTimeOffSet = oCurrentTimeZone.GetUtcOffset(oDateTime);
                oDateTime = oDateTime.AddHours(oTimeOffSet.TotalHours);

                // Assign Server date and tiemvalues to system file time
                SYSTEMTIME SysTime = new SYSTEMTIME();
                SysTime.wYear = (ushort)oDateTime.Year;
                SysTime.wMonth = (ushort)oDateTime.Month;
                SysTime.wDay = (ushort)oDateTime.Day;
                SysTime.wHour = (ushort)oDateTime.Hour;
                SysTime.wMinute = (ushort)oDateTime.Minute;
                SysTime.wSecond = (ushort)oDateTime.Second;

                // if not given error , we will get  set is true;
                SetSystemTime(ref SysTime);

                return true;

            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

       public static bool SetLocalTimeFromYahoo(string RequestURL)
       {

           bool IsCorrectDate = false;
           try
           {

               Double CurrentTimestamp = 0;

               WebRequest Req = WebRequest.Create(RequestURL);

               Req.Proxy = WebProxy.GetDefaultProxy();

               WebResponse Res = Req.GetResponse();

               // Save as Timestamp as a temporary XML file
               String TempFile = Guid.NewGuid().ToString() + ".xml";

               StreamWriter SW = new StreamWriter(TempFile);

               SW.Write(new StreamReader(Res.GetResponseStream()).ReadToEnd());
               SW.Close();

               // Read the XML file and get the Timestamp value

               XmlTextReader MyXML = new XmlTextReader(TempFile);

               while (MyXML.Read())
               {
                   switch (MyXML.NodeType)
                   {
                       case XmlNodeType.Element:
                           if (MyXML.Name == "Timestamp")
                           {

                               CurrentTimestamp = Convert.ToDouble(MyXML.ReadInnerXml());

                           }
                           break;
                   }
               }

               MyXML.Close();

               // Delete the temporary XML file
               FileInfo TFile = new FileInfo(TempFile);

               TFile.Delete();

               // Convert Timestamp to Time
               DateTime MyDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);

               MyDateTime = MyDateTime.AddSeconds(CurrentTimestamp);
               int mydate = MyDateTime.Month;
               int myyear = MyDateTime.Year;
               // August or greate than and Year
               if (mydate >= 8 && myyear >= 2007)
               {
                   IsCorrectDate = false;
               }
               else
               {
                   // Change the system time
                   SYSTEMTIME SysTime = new SYSTEMTIME();
                   SysTime.wYear = (ushort)MyDateTime.Year;
                   SysTime.wMonth = (ushort)MyDateTime.Month;
                   SysTime.wDay = (ushort)MyDateTime.Day;
                   SysTime.wHour = (ushort)MyDateTime.Hour;
                   SysTime.wMinute = (ushort)MyDateTime.Minute;
                   SysTime.wSecond = (ushort)MyDateTime.Second;

                   SetSystemTime(ref SysTime);

                   IsCorrectDate = true;
               }

               return IsCorrectDate;

           }
           catch (Exception ex)
           {
               IsCorrectDate = false;
               return IsCorrectDate;
           }
       }

        #endregion
    }
}

Lets call this utility  in your project.the sample like following,

private void SetTime()
{
	 string sWebYahooTimeServerUrl = "http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo";

	bool bIsSystemTime = TimeUtils.SetLocalTimeFromYahoo(sWebYahooTimeServerUrl);
	if (bIsSystemTime)
	{
		MessageBox.show("Time has been set");
	}
}

I hope this is help to you. if you have any questions  please post in codegain message boards.

 
Sign Up to vote for this article
 
About Author
 
RRaveen
Occupation-Software Engineer
Company-TGS
Member Type-Gold
Location-Singapore
Joined date-03 Jun 2009
Home Page-codegain.com
Blog Page-www.codegain.com
- B.Sc. degree in Computer Science. - 4+ years experience in Visual C#.net and VB.net - Obsessed in OOP style design and programming. - Designing and developing Network security tools. - Designing and developing a client/server application for sharing files among users in a way other than FTP protocol. - Designing and implementing GSM gateway applications and bulk messaging. - Windows Mobile and Symbian Programming - Having knowledge with ERP solutions
 
 
Other popularSectionarticles
    A few days ago I got a message from a developer that was trying to use CeRunAppAtTime to schedule an application to start up. As I had mentioned in a previous post instead of using this function one should use CeSetUserNotification since on more recent devices CeRunAppAtTime is not as reliable
    Published Date : 17/Jul/2010
    A quick implementation of FindControl for Windows Forms.
    Published Date : 11/Jun/2010
Comments
By:RRaveenDate Of Posted:1/21/2011 8:25:36 AM
Its not need
The TimeSyncService is web service for whole application used. you can remove the SetLocalTime method. its not use. thank you
By:AxelDate Of Posted:1/21/2011 3:59:18 AM
Question on TimeSyncService
Hi, what about TimeSyncService? I have no assembly with that name? Could you help, please Thanks Axel
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top