Wednesday, June 26, 2013

Change System date time of windows Mobile

This class will change the system date time  of windows Mobile.
scenario:
sync your mobile time with centralized server.

class TimeSyncer
    {
        [DllImport("coredll.dll")]
        private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);


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

        private DateTime GetDateTime(DateTime currentDateTime)
        {
            double hourOffsetValue;

            // *** Converting time to GMT
            //gmt from india is -5.5 hrs
            hourOffsetValue = -5.5;
            currentDateTime = currentDateTime.AddHours(
            hourOffsetValue);

            return currentDateTime;
        }

        public void SetSystemDateTime(DateTime serverDateTime)
        {
            try
            {
                SYSTEMTIME st = new SYSTEMTIME();

                DateTime updatedDateTime = GetDateTime(
                 serverDateTime);

                st.wYear = (ushort)updatedDateTime.Year;
                st.wMonth = (ushort)updatedDateTime.Month;
                st.wDay = (ushort)updatedDateTime.Day;
                st.wHour = (ushort)updatedDateTime.Hour;
                st.wMinute = (ushort)updatedDateTime.Minute;
                st.wSecond = (ushort)updatedDateTime.Second;

                uint nReturn = SetSystemTime(ref st);


            }
            catch (Exception ex)
            {
                throw;
            }

        }
    }


No comments: