Start New Discussion within our Software Development Community

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.

// this C# program gets the US Naval Observatory Master Clock Time
// SnippetCompiler.exe was used to write, compile (uses .NET V2 csc.exe)
// and run this code, a handy little C# utility free from: 
// http://www.sliver.com/dotnet/SnippetCompiler/

using System;
using System.Net;   // HttpWebRequest
using System.IO;    // StringReader
using System.Text;  // StringBuilder

class NavyTime 
{
  static public void Main(string[] args)
  {
    string navyURL = "http://tycho.usno.navy.mil/cgi-bin/timer.pl";
    string htmlTimeStr = GetHTML(navyURL);

    string strMyDateTime = null;
    StringReader strReader = new StringReader(htmlTimeStr);
    string line;
    // extract the Pacific Time Zone information 
    while ((line = strReader.ReadLine()) != null) 
    {
      // use the Pacific Time Zone line 
      int pos = line.LastIndexOf("PDT");
      if (pos != -1)
      {
        //start from pos 4 because of the <BR> tag
        strMyDateTime = line.Substring(4, pos - 4); 
        break;
      }
    }
    Console.WriteLine("Raw HTML_code time information:");
    Console.WriteLine(htmlTimeStr);
    // sorry, the US Navy does not supply the year
    Console.WriteLine("Pacific Time Zone time:");
    Console.WriteLine(strMyDateTime);
    
    Console.Write("\nPress Enter to exit ...");
    Console.Read();  // console display, wait for key
  }
  
  // extract the HTML code with time information
  static string GetHTML(string url)
  {
    StringBuilder sb1 = new StringBuilder();
    byte[] buf1 = new byte[4096];

    HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream resStream = response.GetResponseStream();
    string tempString = null;
    int count = 0;

    while (0 < (count = resStream.Read(buf1, 0, buf1.Length)))
    {
      tempString = Encoding.ASCII.GetString(buf1, 0, count);
      sb1.Append(tempString);
    }
    return sb1.ToString();
  }
}
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.