views:

76

answers:

3

how to calculate the other country time. using my local machine time in c#?

Example:

My system having India time and my array contains all the countries GMT time.

How to do the calculation to get the other country time?

if my time is 5.00 P.M if the country is Pakistan it should show 4.30 p.m

+3  A: 

Assuming you're using .NET 3.5 or higher, you need to get the right TimeZoneInfo (e.g. by ID). From then on, it's fairly simple - I'd suggest that you use UTC wherever it's available, and probably DateTimeOffset rather than DateTime as that's less ambiguous. Take your current time with DateTimeOffset.UtcNow, get the appropriate time zone to convert to, and then use TimeZoneInfo.ConvertTime(DateTimeOffset, TimeZoneInfo). That will get you the appropriate new DateTimeOffset (i.e. offset by the appropriate amount in the target time zone) which you can then format appropriately.

Jon Skeet
A: 

To begin with what you can do is that you can write a function in which you can pass both the current time(of INDIA) and the time difference (in terms of +hrs:min or - hrs:min) . Your code can then compute the result and pass it back.

string time(string IndiaTime, string timeDifference) { string array1 = IndiaTime.split(':'); // Over here I have considered you have passed the time in 24 hour format. int timeinMinutes = Convert.ToInt32(array1[0])*60 + Convert.ToInt32(array[1]); timeinMinutes = timeinMinutes + timeDifference; int minutes = time % 60 ; int hour = time / 60; If (hour > 24 ) hour = hour - 24; String finalTime = Convert.ToString(hour) + ":" + Convert.ToString(minutes); return finalTime; }

Apart from this you can use various inbuilt C# classes as posted above.

Egalitarian
You couldn't have described a worse way to do this if you tried. Using strings for both date and timeDifference :|
Jamiec
A: 

First, be sure that your DateTime has DateTimeKind.Local (or is UTC with valid UTC time already). If it doesn't you can convert this:

myDate.SpecifyDateTimeKind(DateTimeKind.Local)

(Do it as close to where the date is created as possible; saves confusion later.)

Now find the timezone for the country you're interested in:

// In case you don't know what the key is:
var allTimeZones = TimeZone.GetSystemTimeZones();

// Then when you have the key:
var theirTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneKey);
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(myDateTime, theirTimeZone);

Hope that helps.

Lunivore