I want to get the real current date in C#. Currently I am facing an issue that if someone changes the system time, it will show wrong time and date. I used DateTime.Now
. But it's not working in this case. Thanks in advance.
Asked
Active
Viewed 385 times
-1

marc_s
- 732,580
- 175
- 1,330
- 1,459

Parag Vasant
- 1
- 6
-
5Use NTP-Server: http://stackoverflow.com/questions/1193955/how-to-query-an-ntp-server-using-c – Sebastian Schumann Jul 07 '15 at 09:10
2 Answers
5
Get it from NIST
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);
}
And make sure port 13 is not blocked.

fishmong3r
- 1,414
- 4
- 24
- 51
0
DateTime.Now
is returning the time as expected: that's dictated by the system.
Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.
If you want to rely on "real time", you'll need to go on further and reconcile with something like one of the NIST time servers - this way you can match, and inform of inconsistencies or whatever you need to do that relies on time in the real world and not as stated by a human-editable time on a single machine.

Grant Thomas
- 44,454
- 10
- 85
- 129