How to set SystemTime in Windows Mobile using C#

來源:互聯網
上載者:User
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.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.