-2

If I'll write Datetime.Now; .net says that it's

2/23/2015 5:24:41 PM

but if I'll change my calender of computer to 16'th February. It says:

2/16/2015 5:24:41 PM

How can I say to C# that you must get global time and not time of my computer?

Same on Datetime.UtcNow;

gsiradze
  • 4,583
  • 15
  • 64
  • 111
  • 2
    You mean, go out to an NTP server and get the real time, rather than your computer time? Usually you set up your OS to take care of that. What's the problem you're trying to solve? – dsolimano Feb 23 '15 at 13:31
  • PC has one source of time - BIOS clocks (which counts up even when PC is off). If you change that (by changing calendar), then you change date **on your PC**. To get what you call global time you need to have another time storage (some external device, or web-site). Is that what you are asking? – Sinatr Feb 23 '15 at 13:33
  • Or see http://stackoverflow.com/questions/1193955/how-to-query-an-ntp-server-using-c – xanatos Feb 23 '15 at 13:34
  • 1
    Check the following link. [1]: http://stackoverflow.com/questions/6676191/how-can-get-datetime-from-internet-external-resource-not-from-server – itzmebibin Feb 23 '15 at 13:35
  • @dsolimano I need to write some auction logic which will lasts only 1 week. after this week will new items there etc. for that i need that client can't change this time. is there any better way? – gsiradze Feb 23 '15 at 13:36
  • 1
    @George - don't trust the client with time at all if its critical to getting things right. Have a central server that acts as a "source of truth" for when things happened, and in what order. – Damien_The_Unbeliever Feb 23 '15 at 13:53

2 Answers2

2

Here is code sample that you can use to retrieve time from NIST Internet Time Service.

var client = new TcpClient("time.nist.gov", 13);
using (var streamReader = new StreamReader(client.GetStream()))
{
    var response = streamReader.ReadToEnd();
    var utcDateTimeString = response.Substring(7, 17);
    var localDateTime = DateTime.ParseExact(utcDateTimeString, "yy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
}
Utsav Dawn
  • 7,896
  • 2
  • 29
  • 44
1

You cannot (with standard .NET)

The 'DateTime.UtcNow' suggested by some returns (per MSDN):

Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).

You have to find an online time provider and hook to it.

See here: Free Rest API to get current time as string (timezone irrelevant)

Community
  • 1
  • 1
Gerino
  • 1,943
  • 1
  • 16
  • 21