Get current time from server and convert it to local time in C #

Help: I ​​have a server that has a time in GMT-07.00. My local time is GMT + 05.30 hours. I need to get the current date and time from the server and convert this date and time to my local time. I tried a lot of codes, but still have not found a consistent way to do this. Can someone please help me.

string zoneId = "India Standard Time";
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
DateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);
DateTime cu = result.ToUniversalTime();
DateTime cur = cu.ToLocalTime();

I have tried all of the above methods, but I am not getting the correct answer. Suppose my current local time is March 09, 2014 12:51:00, then my server time will be 12.30 hours different from my local time, that is, subtract 12 hours and 30 minutes from my local time to get the time of my server . I need to get local time from the server. How can I get this? Please suggest me some solutions. Thanks in advance for your answers.

+4
source share
5 answers

no need to know the time zone of the server. if the server time setting is correct, you can try the following:

DateTime serverTime = DateTime.Now; // gives you current Time in server timeZone
DateTime utcTime = serverTime.ToUniversalTime(); // convert it to Utc using timezone setting of server computer

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, tzi); // convert from utc to local

, , . . , .

:

, . :

DateTime utcTime = DateTime.UtcNow;
+5

12 30 , ( , ), AddHours() AddMinutes(), 12:30

:

DateTime dt= /*your server time*/;
dt=dt.AddHours(12);
dt=dt.AddMinutes(30);
+1

, , ? :

//Server: 09-Mar-2014 11:00:00 AM:
var serverTime = new DateTime(2014, 3, 9, 11, 00, 00);

var serverZone = TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time");
var localZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");

var localTime = TimeZoneInfo.ConvertTime(serverTime, serverZone, localZone);
// => 09-Mar-2014 11:30:00 PM
0

If the server clock is set correctly (regardless of the time zone), then the first three lines of your own code are exactly correct. The variable resultcontains local time in the time zone of India.

Just omit the last two lines.

0
source
 DateTime serverTime = DateTime.Now;

 DateTime utcTime = serverTime.ToUniversalTime(); 

// convert it to Utc using timezone setting of server computer

 TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");

 DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, tzi); 

// convert from utc to local
0
source

Source: https://habr.com/ru/post/1530808/


All Articles