US Naval Observatory Master Clock Time (C#)

Please support our C# advertiser: $4.95 a Month - ASP.NET Web Hosting – Click Here!
vegaseat vegaseat is offline Offline Apr 19th, 2007, 3:52 pm |
0
A short C# code snippet to get the US Naval Observatory Master Clock Time from:
http://tycho.usno.navy.mil/cgi-bin/timer.pl
The snippet displays the raw HTML code with the time infomation and then extracts one specific US time zone.
Quick reply to this message  
C# Syntax
  1. // this C# program gets the US Naval Observatory Master Clock Time
  2. // SnippetCompiler.exe was used to write, compile (uses .NET V2 csc.exe)
  3. // and run this code, a handy little C# utility free from:
  4. // http://www.sliver.com/dotnet/SnippetCompiler/
  5.  
  6. using System;
  7. using System.Net; // HttpWebRequest
  8. using System.IO; // StringReader
  9. using System.Text; // StringBuilder
  10.  
  11. class NavyTime
  12. {
  13. static public void Main(string[] args)
  14. {
  15. string navyURL = "http://tycho.usno.navy.mil/cgi-bin/timer.pl";
  16. string htmlTimeStr = GetHTML(navyURL);
  17.  
  18. string strMyDateTime = null;
  19. StringReader strReader = new StringReader(htmlTimeStr);
  20. string line;
  21. // extract the Pacific Time Zone information
  22. while ((line = strReader.ReadLine()) != null)
  23. {
  24. // use the Pacific Time Zone line
  25. int pos = line.LastIndexOf("PDT");
  26. if (pos != -1)
  27. {
  28. //start from pos 4 because of the <BR> tag
  29. strMyDateTime = line.Substring(4, pos - 4);
  30. break;
  31. }
  32. }
  33. Console.WriteLine("Raw HTML_code time information:");
  34. Console.WriteLine(htmlTimeStr);
  35. // sorry, the US Navy does not supply the year
  36. Console.WriteLine("Pacific Time Zone time:");
  37. Console.WriteLine(strMyDateTime);
  38.  
  39. Console.Write("\nPress Enter to exit ...");
  40. Console.Read(); // console display, wait for key
  41. }
  42.  
  43. // extract the HTML code with time information
  44. static string GetHTML(string url)
  45. {
  46. StringBuilder sb1 = new StringBuilder();
  47. byte[] buf1 = new byte[4096];
  48.  
  49. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  50. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  51. Stream resStream = response.GetResponseStream();
  52. string tempString = null;
  53. int count = 0;
  54.  
  55. while (0 < (count = resStream.Read(buf1, 0, buf1.Length)))
  56. {
  57. tempString = Encoding.ASCII.GetString(buf1, 0, count);
  58. sb1.Append(tempString);
  59. }
  60. return sb1.ToString();
  61. }
  62. }
0
Mustafa Laith Mustafa Laith is offline Offline | Sep 24th, 2007
Thanks For All
 
 

Message:


Similar Threads
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC