locked
how to convert utc time to client system time RRS feed

  • Question

  • dear sir,

    am developing an online server windows application using c#.net. my server is from USA and my users are in India. for getting correct time i create a procedure for GETDATE() to retrieve  server time. so in my application it shows US time. but i want indian time. how should i achieve this in my code? plz help me sir....

    note my application is windows.. 

    i use below code but it shows a three minutes difference from actual time.

     date = Convert.ToDateTime(dt.Rows[0][0].ToString());
                   date= TimeZone.CurrentTimeZone.ToLocalTime(date);
    Tuesday, April 19, 2016 5:59 AM

Answers

  • Hi Mousmi Nishad,

    You could try the following code:

        /// <summary>  
        /// NetTime  
        /// </summary>  
        public static class NetTime
        {
            //setLocalTime api
            [DllImport("kernel32.dll")]
            private static extern bool SetLocalTime(ref SYSTEMTIME time);
    
            [StructLayout(LayoutKind.Sequential)]
            private struct SYSTEMTIME
            {
                public short year;
                public short month;
                public short dayOfWeek;
                public short day;
                public short hour;
                public short minute;
                public short second;
                public short milliseconds;
            }
            public static DateTime GetNistTime()
            {
                DateTime dateTime = DateTime.MinValue;
    
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://nist.time.gov/actualtime.cgi?lzbc=siqm9b");
                request.Method = "GET";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
                request.ContentType = "application/x-www-form-urlencoded";
                request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); //No caching
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader stream = new StreamReader(response.GetResponseStream());
                    string html = stream.ReadToEnd();//<timestamp time=\"1395772696469995\" delay=\"1395772696469995\"/>
                    string time = Regex.Match(html, @"(?<=\btime="")[^""]*").Value;
                    double milliseconds = Convert.ToInt64(time) / 1000.0;
                    dateTime = new DateTime(1970, 1, 1).AddMilliseconds(milliseconds).ToLocalTime();
                }
    
                return dateTime;
            }
    
    
            /// <summary>
            /// SetDate
            /// </summary>
            /// <param name="dt">date</param>
            /// <returns></returns>
            public static bool SetDate(DateTime dt)
            {
                SYSTEMTIME st;
    
                st.year = (short)dt.Year;
                st.month = (short)dt.Month;
                st.dayOfWeek = (short)dt.DayOfWeek;
                st.day = (short)dt.Day;
                st.hour = (short)dt.Hour;
                st.minute = (short)dt.Minute;
                st.second = (short)dt.Second;
                st.milliseconds = (short)dt.Millisecond;
                bool rt = SetLocalTime(ref st);
                return rt;
            }
    
        }

    Use:

                //Sample();
                DateTime nettime = NetTime.GetNistTime();
                if (NetTime.SetDate(nettime))
                {
                    MessageBox.Show("Success!");
                }
            

    Regards,

    Moonlight


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    • Marked as answer by Mousmi Nishad Wednesday, April 20, 2016 4:38 AM
    Wednesday, April 20, 2016 1:46 AM

All replies

  • Hi Mousim Nishad,

    You could try to use following code:

    //server
                DateTime dt = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now, TimeZoneInfo.Local);//server time to utc time
    //client
                DateTime dtlocal = dt.ToLocalTime();//client get the server's utc time and transfer to local

    Reference links:

    Converting Times Between Time Zones

    Finding the Time Zones Defined on a Local System

    Regards,

    Moonlight


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.




    Tuesday, April 19, 2016 6:19 AM
  • I think that instead of calling GETDATE on SQL server, then converting to local time, you can simply call DateTime.Now.

    The difference between dates can be caused by imprecise machine clocks.

    You are probably already aware about the usual recommendation to store UTC dates to databases (GETUTCDATE and DateTime.UtcNow) instead of local dates.


    • Edited by Viorel_MVP Tuesday, April 19, 2016 6:39 AM
    Tuesday, April 19, 2016 6:38 AM
  • 

    I think that instead of calling GETDATE on SQL server, then converting to local time, you can simply call DateTime.Now.

    The difference between dates can be caused by imprecise machine clocks.

    i use GETDATE() to get server time. am doing online database in windows application. and it is time based application. DateTime.Now will take current time client pc but in every situations the time won't be correct. so i use GETDATE(). if u have other solutions plz let me know. thankz in advance. 

    Tuesday, April 19, 2016 8:11 AM
  • Moonlight Sheng sir your code works.. but it show three minute difference from correct time..
    Tuesday, April 19, 2016 8:13 AM
  • Hi Mousmi Nishad,

    >>The difference between dates can be caused by imprecise machine clocks.

    I think you could add a network time synchronization method(server and client) and call the method when application open.

    Regards,

    Moonlight


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Tuesday, April 19, 2016 8:32 AM
  • can u plz tell me how to use that...plz sir
    Tuesday, April 19, 2016 9:57 AM
  • Hi Mousmi Nishad,

    You could try the following code:

        /// <summary>  
        /// NetTime  
        /// </summary>  
        public static class NetTime
        {
            //setLocalTime api
            [DllImport("kernel32.dll")]
            private static extern bool SetLocalTime(ref SYSTEMTIME time);
    
            [StructLayout(LayoutKind.Sequential)]
            private struct SYSTEMTIME
            {
                public short year;
                public short month;
                public short dayOfWeek;
                public short day;
                public short hour;
                public short minute;
                public short second;
                public short milliseconds;
            }
            public static DateTime GetNistTime()
            {
                DateTime dateTime = DateTime.MinValue;
    
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://nist.time.gov/actualtime.cgi?lzbc=siqm9b");
                request.Method = "GET";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
                request.ContentType = "application/x-www-form-urlencoded";
                request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); //No caching
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader stream = new StreamReader(response.GetResponseStream());
                    string html = stream.ReadToEnd();//<timestamp time=\"1395772696469995\" delay=\"1395772696469995\"/>
                    string time = Regex.Match(html, @"(?<=\btime="")[^""]*").Value;
                    double milliseconds = Convert.ToInt64(time) / 1000.0;
                    dateTime = new DateTime(1970, 1, 1).AddMilliseconds(milliseconds).ToLocalTime();
                }
    
                return dateTime;
            }
    
    
            /// <summary>
            /// SetDate
            /// </summary>
            /// <param name="dt">date</param>
            /// <returns></returns>
            public static bool SetDate(DateTime dt)
            {
                SYSTEMTIME st;
    
                st.year = (short)dt.Year;
                st.month = (short)dt.Month;
                st.dayOfWeek = (short)dt.DayOfWeek;
                st.day = (short)dt.Day;
                st.hour = (short)dt.Hour;
                st.minute = (short)dt.Minute;
                st.second = (short)dt.Second;
                st.milliseconds = (short)dt.Millisecond;
                bool rt = SetLocalTime(ref st);
                return rt;
            }
    
        }

    Use:

                //Sample();
                DateTime nettime = NetTime.GetNistTime();
                if (NetTime.SetDate(nettime))
                {
                    MessageBox.Show("Success!");
                }
            

    Regards,

    Moonlight


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    • Marked as answer by Mousmi Nishad Wednesday, April 20, 2016 4:38 AM
    Wednesday, April 20, 2016 1:46 AM
  • its working sir..thank you so much..
    Wednesday, April 20, 2016 4:39 AM