Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to retrieve accurate date?

Tags:

date

c#

winforms

What is the best way to retrieve the current date? Currently I am storing the date like this:

string date = DateTime.Now.ToString("yyyyMMdd");

Obviously, if the user changes the date on their system, this will also be affected.

I need a way to access an accurate date (preferable in central time) and store it as a string within my application. Any ideas?

like image 226
user Avatar asked Nov 20 '25 02:11

user


2 Answers

Define "accurate"? If you cannot trust the system date, then you need to get the time from an outside source (ie, atomic clock). But the user may block your program from getting it (ie, unplugging the network cable, blocking your time query with a software firewall).

So what is it that you really want?

like image 91
Gabriel Magana Avatar answered Nov 22 '25 15:11

Gabriel Magana


EDIT: This works, give it a try:

private string GetCurrentDateTime()
{
    WebRequest request = WebRequest.Create(@"http://developer.yahooapis.com/TimeService/V1/getTime?appid=Test");
    // request.Proxy = new WebProxy("PROXYSERVERNAME", 8080); // You may or may not need this
    WebResponse response = request.GetResponse();      

    Double currentTimeStamp = 0;
    using (Stream stream = response.GetResponseStream())
    {
        using (XmlTextReader xmlReader = new XmlTextReader(stream))
        {
            while (xmlReader.Read())
            {
                switch (xmlReader.NodeType)
                {
                    case XmlNodeType.Element:
                        if (xmlReader.Name == "Timestamp")
                        {
                            currentTimeStamp = Convert.ToDouble(xmlReader.ReadInnerXml());
                        }
                        break;
                }
            }

            xmlReader.Close();
        }
    }

    DateTime yahooDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return yahooDateTime.AddSeconds(currentTimeStamp).AddHours(2).ToString("yyyyMMdd");     
}
like image 27
Philip Wallace Avatar answered Nov 22 '25 16:11

Philip Wallace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!