I've a C#
Program what needs to convert from EST to UTC. Following function works perfectly in Linux
except the fact that it's adding an hour extra means rather than adding 4 hours, it's adding 5 hours. This is because of DayLightSaving.
I've tried to use
TimeZoneInfo.Local.IsDaylightSavingTime()
but it's returning wrong value in Linux
Ubuntu -- It should be true but returning as false.
How can I solve this issue in Linux
?
private DateTime ConvertToUTCHHmm(DateTime dateValue)
{
// default to date for debuging, should be overwritten
DateTime dateTimeUtc = DateTime.Now.AddYears(-120);
try
{
// Convert EST to UTC - Old Method of conversion.
TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
dateTimeUtc = TimeZoneInfo.ConvertTimeToUtc(dateValue, est);
// Check Daylight Saving Time..
DateTime thisTime = DateTime.Now;
bool isDaylight = TimeZoneInfo.Local.IsDaylightSavingTime(thisTime);
_logger.LogDebug(String.Format(" IsDaylightSavingTime : {0}", isDaylight));
if (isDaylight) // returns as false. It supposed to be true
dateTimeUtc = dateTimeUtc.AddHours(-1);
_logger.LogDebug(String.Format("TimeZoneInfo Old Process : {0} Converted Time : {1}", est, dateTimeUtc));
}
catch (Exception ex)
{
_logger.LogError("TimeZoneInfo Old Process Error - " + ex.Message);
}
return dateTimeUtc;
}
Finally we fixed the issue. Issue was with this line -
bool isDaylight = TimeZoneInfo.Local.IsDaylightSavingTime(thisTime);
We can't get the New York timezone with Local as Server is running in UTC. So we had to change the code to get New York TimeZone and everything worked perfectly.
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
Here is the full method.
private DateTime ConvertToUTCHHmm(DateTime dateValue)
{
// default to date for debuging, should be overwritten
DateTime dateTimeUtc = DateTime.Now.AddYears(-120);
try
{
// Convert EST to UTC - Old Method of conversion.
TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
dateTimeUtc = TimeZoneInfo.ConvertTimeToUtc(dateValue, est);
// Check Daylight Saving Time..
DateTime thisTime = DateTime.Now;
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
bool isDaylight = tst.IsDaylightSavingTime(thisTime);
_logger.LogDebug(String.Format(" IsDaylightSavingTime : {0}", isDaylight));
if (isDaylight)
dateTimeUtc = dateTimeUtc.AddHours(-1);
_logger.LogDebug(String.Format("TimeZoneInfo Old Process : {0} Converted Time : {1}", est, dateTimeUtc));
}
catch (Exception ex)
{
_logger.LogError("TimeZoneInfo Old Process Error - " + ex.Message);
}
return dateTimeUtc;
}