现在的位置: 首页 > 综合 > 正文

How to set SystemTime in Windows Mobile using C#

2013年06月17日 ⁄ 综合 ⁄ 共 4133字 ⁄ 字号 评论关闭

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.

抱歉!评论已关闭.