Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current date time from server and convert it into local time in c#

Help: I have a server which is having time in GMT-07.00 hours. My local time is GMT+05.30 hours. I need to get current date and time from server and convert this date and time into my local time. I have tried many codes, but still have not found a successive way of doing this. Can somebody please help me out.

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 the above methods, still I'm not getting the correct answer. Suppose my current local time is 09-Mar-2014 12:51:00 PM, then my server time would be 12.30 hours different from my local time, ie subtract 12 hours and 30 minutes from my local time to get my server time. I need to get my local time from the server time. How can it be acheived?? Please suggest me some solutions.. Thanks in advance for your answers

like image 1000
njnjnj Avatar asked Mar 09 '14 07:03

njnjnj


Video Answer


2 Answers

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

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

to check it locally , change your computer timezone to match your server. then run the code. I check and it's working fine.

update:

the first two lines can be mixed into one line as below . that has a better performance :

DateTime utcTime = DateTime.UtcNow;
like image 57
mohsen dorparasti Avatar answered Oct 12 '22 04:10

mohsen dorparasti


if you want to add 12 Hours and 30 minutes to your Server time to get equavalent localtime(assuming you have server time), you can use AddHours() and AddMinutes() functions to add the 12:30 hours

Try This:

DateTime dt= /*your server time*/;
dt=dt.AddHours(12);
dt=dt.AddMinutes(30);
like image 28
Sudhakar Tillapudi Avatar answered Oct 12 '22 05:10

Sudhakar Tillapudi