Click here to Skip to main content
13,259,539 members (58,382 online)
Click here to Skip to main content
Add your own
alternative version


20 bookmarked
Posted 24 May 2007

Windows System Time Synchronizer

, 24 May 2007
Rate this:
Please Sign up or sign in to vote.
This utility synchronizes Windows system time with the Yahoo! server time using a web service

Screenshot - Article.gif


This is a simple utility written in C# .NET Version 2.0. It synchronizes Windows system time with Yahoo! server time through a web service offered by Yahoo!.

Using the code

The utility makes an HTTP request to the Yahoo! URL, which returns Yahoo! server time as a timestamp in XML format. Then the XML is parsed to get the timestamp and is converted into regional date-time. Windows system time is modified to this using a P-Invoke function call.

 * FILE NAME    :    Program.cs
 * DATE CREATED :    March 06, 2007, 12:05:54 PM
 * CREATED BY   :    Gunasekaran Paramesh
 * LAST UPDATED :    April 25, 2007, 12:38:12 PM
 * UPDATED BY   :    Gunasekaran Paramesh
 * DESCRIPTION  :    Synchronizes Windows System Time with Yahoo! Server Time.

using System;
using System.Net;
using System.Xml;
using System.IO;
using System.Threading;
using System.Diagnostics;
using Microsoft.Win32;
using System.Configuration;
using System.Runtime.InteropServices;

namespace TryWinTimeSync
    class Program
        public struct SYSTEMTIME 
            public short wYear;
            public short wMonth;
            public short wDayOfWeek;
            public short wDay;
            public short wHour;
            public short wMinute;
            public short wSecond;
            public short wMilliseconds;

        [DllImport("kernel32.dll", SetLastError=true)]
        public static extern bool SetSystemTime( [In] ref SYSTEMTIME st );

        static void Main(string[] args)
            BooleanSwitch Tracer = new BooleanSwitch("TraceSwitch", 
                "Trace for entire application");
            EventLog Log = null;

                // Initialize EventLog
                Log = new EventLog();
                        "WinTimeSync", "Zion");
                Log.Source = "WinTimeSync";
                Log.Log = "Zion";
                if ( Tracer.Enabled )
                    Trace.Listeners.Add(new EventLogTraceListener(Log));

                Trace.WriteLineIf(Tracer.Enabled, "Starting WinTimeSync...");

                Boolean ServiceAlive = true;
                Double CurrentTimestamp = 0;

                    "Opening configuration file for initializing" + 
                    " global settings...");

                Int32 SyncInterval = Convert.ToInt32(
                String RequestURL = ConfigurationSettings.AppSettings[

                    "Global settings initialized [SyncInterval: " + 
                    SyncInterval + " minutes; RequestURL: " + 
                    RequestURL + "]");

                while ( ServiceAlive )
                    "Synchronizing system time with time server...");

                    // Send HTTP request for Timestamp
                        "Creating HTTP request to [" + RequestURL + "]");
                    WebRequest Req = WebRequest.Create(RequestURL);
                        "Setting default proxy for the HTTP request...");
                    Req.Proxy = WebProxy.GetDefaultProxy();
                        "Sending HTTP request...");
                    WebResponse Res = Req.GetResponse();

                    // Save as Timestamp as a temporary XML file
                    String TempFile = Guid.NewGuid().ToString() + ".xml";
                        "Creating a temporary XML file [" + TempFile + "]");
                    StreamWriter SW = new StreamWriter(TempFile);
                        "Saving HTTP response to the temporary XML file...");
                    SW.Write(new StreamReader(

                    // Read the XML file and get the Timestamp value
                        "Opening the temporary XML file...");
                    XmlTextReader MyXML = new XmlTextReader(TempFile);
                        "Reading the temporary XML file...");
                    while ( MyXML.Read() )
                        switch ( MyXML.NodeType )
                            case XmlNodeType.Element:
                            if ( MyXML.Name == "Timestamp" )
                                    "Retriving the current timestamp" + 
                                    " from the temporary XML file...");
                                CurrentTimestamp = Convert.ToDouble(
                                    "Current timestamp retrived [
                                    " + CurrentTimestamp + "]");
                        "Closing the temporary XML file...");

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

                    // Convert Timestamp to Time
                    DateTime MyDateTime = 
                        new DateTime(1970, 1, 1, 0, 0, 0, 0);
                        "Converting the timestamp to time...");
                    MyDateTime = MyDateTime.AddSeconds(CurrentTimestamp);
                        "Timestamp converted to time [
                        " + MyDateTime.ToLocalTime() + "]");

                    // Change the system time
                    SYSTEMTIME SysTime = new SYSTEMTIME();
                    SysTime.wYear = (short) MyDateTime.Year;
                    SysTime.wMonth = (short) MyDateTime.Month; 
                    SysTime.wDay = (short) MyDateTime.Day;
                    SysTime.wHour = (short) MyDateTime.Hour;
                    SysTime.wMinute = (short) MyDateTime.Minute;
                    SysTime.wSecond = (short) MyDateTime.Second;
                        "Setting the system time...");
                    SetSystemTime(ref SysTime);

                        "Switching to sleep state until SyncInterval...");
                    for ( int i = 0; i < SyncInterval; i++ )
                        Thread.Sleep(1000 * 60);
                            "Switching back to active mode...");
            catch ( Exception Ex )
                // Log for errors                
                if ( Tracer.Enabled )
                    Log.WriteEntry(Ex.StackTrace, EventLogEntryType.Error);
                    Log.WriteEntry(Ex.Message, EventLogEntryType.Error);

Sample configuration file

Below is the sample configuration file. TraceSwitch is used to enable debug log messages. SyncInterval specifies the elapsed time in seconds where the utility synchronizes the Windows system time with the Yahoo! time server. TimeServerURL specifies the actual Yahoo! URL which, on request, returns the server time.

            <add name="TraceSwitch" value="1" />
        <add key="SyncInterval" value="60" />
        <add key="TimeServerURL" value=
"" />


  • Baseline v1.0 - April 25, 2007


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Paramesh Gunasekaran
Technical Lead HCL Technologies
India India
Paramesh Gunasekaran is currently working as a Software Engineer in HCL Technologies, India. He obtained his Bachelor's degree in Information Technology from Anna University, India. His research areas include Computational Biology, Artificial Neural Networks and Network Engineering. He has also received international acclaim for authoring industry papers in these areas. He is a Microsoft Certified Professional in ASP.NET/C# and has also been working in .NET technologies for more than 8 years.


You may also be interested in...


Comments and Discussions

GeneralMy vote of 1 Pin
Diptimoy12347-Dec-11 19:24
memberDiptimoy12347-Dec-11 19:24 
GeneralNTP Pin
Wael Al Wirr9-Aug-07 4:21
memberWael Al Wirr9-Aug-07 4:21 
Generalit visits strange adds sites ?! Pin
andré_k17-Jul-07 22:02
memberandré_k17-Jul-07 22:02 
QuestionWhy this when there is NTP? Pin
Ramon Smits24-May-07 5:12
memberRamon Smits24-May-07 5:12 
AnswerRe: Why this when there is NTP? Pin
Gunasekaran Paramesh24-May-07 8:55
memberGunasekaran Paramesh24-May-07 8:55 
GeneralRe: Why this when there is NTP? Pin
Ramon Smits24-May-07 12:41
memberRamon Smits24-May-07 12:41 
AnswerRe: Why this when there is NTP? Pin
sillett24-May-07 15:40
membersillett24-May-07 15:40 
GeneralRe: Why this when there is NTP? Pin
Ramon Smits24-May-07 22:31
memberRamon Smits24-May-07 22:31 
GeneralRe: Why this when there is NTP? Pin
sillett25-May-07 2:54
membersillett25-May-07 2:54 
AnswerRe: Why this when there is NTP? Pin
Ramon Smits25-May-07 3:02
memberRamon Smits25-May-07 3:02 
GeneralRe: Why this when there is NTP? Pin
JLester29-May-07 4:11
memberJLester29-May-07 4:11 
AnswerRe: Why this when there is NTP? Pin
Ramon Smits29-May-07 5:51
memberRamon Smits29-May-07 5:51 
GeneralRe: Why this when there is NTP? Pin
JLester29-May-07 6:26
memberJLester29-May-07 6:26 
I'll restate not all real world issues are as black and white as "Any other method shouldn't be used at all". Just because the ports should be opened up, which I agree with, doesn't mean they will be.

The fact that you would question someone’s skill because of a restriction, that may or may not be out of the persons control, shows just how short sighted you are. I'd love to hire someone who is able to solve a problem in more than one way depending on the external conditions.

Would I have prefered to use NTP, yes. Did I look into it, yes. Unfortunatly, in my "real world" application this was the only method available to synchronize the time on the machine, and I appreciate the article and hope Param posts more.

AnswerRe: Why this when there is NTP? Pin
AndyCLon28-May-07 23:21
memberAndyCLon28-May-07 23:21 
GeneralRe: Why this when there is NTP? Pin
CrazyTasty28-Jun-13 9:01
memberCrazyTasty28-Jun-13 9:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171114.1 | Last Updated 24 May 2007
Article Copyright 2007 by Paramesh Gunasekaran
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid