I have a method that calculates the time offset between the user's time and the UTC time that works like this:
public int GetUserLocalTimeToUTCOffset()
{
DateTime TheUTC = DateTime.UtcNow;
DateTime TheLocal = ConvertUTCTimeToUserTime(TheUTC); //*see below
TimeSpan TheTimeOffset = TheLocal - TheUTC;
return (int)TheTimeOffset.TotalMinutes;
}
public DateTime ConvertUTCTimeToUserTime(DateTime TheUTCTime)
{
TimeZoneInfo TheTZ = TimeZoneInfo.FindSystemTimeZoneById(this.UserTimeZoneID);
// try with "Eastern Standard Time" and "W. Europe Standard Time"
DateTime UTCTime = new DateTime(TheUTCTime.Year, TheUTCTime.Month, TheUTCTime.Day, TheUTCTime.Hour, TheUTCTime.Minute, 0, DateTimeKind.Utc);
return TimeZoneInfo.ConvertTime(UTCTime, TheTZ);
}
If the user is in the EST timezone, the method returns -300 (ie 60 * -5). However, if the user is in Europe western time then the method returns 59 instead of 60. Not that big of a biggie but I was wondering why it's not returning 60 and what changes I need to make.
Thanks.
The property TotalMinutes returns a double. My guess is that casting it to an int rounds down the value.
Try rounding up your value before returning it. I would modify your return statement to this to have the value of total minutes rounded up.
return (int)Math.Ceiling(TheTimeOffset.TotalMinutes);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.