New Blog Address

Blog moved to

Dear blog reader,
I moved my content to and will not add any new post here.

It was a pleasure to have you as my reader here.

Stay safe and healthy!

I will shortly redirect you to my new blog address...

Wrong DateTime on .NET Micro Framework Devices

Tags: .NET, .NET Micro Framework, Source Code

Since embeddedworld2008 in Nuremberg I'm playing in my free time with the .NET Micro Framework and the Digi Connect ME network device. I've created a small Web server and ported the Ajax.NET Professional library to the really cool and small .NET framework.

When I reset such a device the current date and time gets wrong, too. This is very bad as I would like to have always the correct time, of course. Especially when you are working with Web servers it is very important to have the correct time because http headers contain date info when files should expire or how long they are allowed to be cached locally in Web browsers cache.

I have created a simple method to query a NTP server and set the device date to the returned value. Here is the code:

public static DateTime GetNetworkTime() { IPEndPoint ep = new IPEndPoint(Dns.GetHostEntry("").AddressList[0], 123); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); s.Connect(ep); byte[] ntpData = new byte[48]; // RFC 2030 ntpData[0] = 0x1B; for (int i = 1; i < 48; i++) ntpData[i] = 0; s.Send(ntpData); s.Receive(ntpData); byte offsetTransmitTime = 40; ulong intpart = 0; ulong fractpart = 0; for (int i = 0; i <= 3; i++) intpart = 256 * intpart + ntpData[offsetTransmitTime + i]; for (int i = 4; i <= 7; i++) fractpart = 256 * fractpart + ntpData[offsetTransmitTime + i]; ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L); s.Close(); TimeSpan timeSpan = TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond); DateTime dateTime = new DateTime(1900, 1, 1); dateTime += timeSpan; TimeSpan offsetAmount = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime); DateTime networkDateTime = (dateTime + offsetAmount); Debug.Print(networkDateTime.ToString()); return networkDateTime; }

To set the returned DateTime as new time on the device use following utility method:


Note, that the current time zone is often wrong, too. Use following method to set the time zone to the correct value, in my example I use the time zone here in Germany:


I put this code in the Main() method of my applications to get always the correct date when I start my device.

No Comments