I have a webjob in azure involves taking a string value and converting it to a DateTime value. The problem is that I want the function to assume that this time is initially entered in central time (CST) and then convert that to universal time. When I run this function locally, everything works as expected. I believe the problem is that when the function is running from the azure server it assumes all times are in UTC to begin with (therefore attempting to convert it to UTC doesnt change it at all).
Here is my code:
function(string date)
{
return DateTime.SpecifyKind(Clean<DateTime>(date.ToString()). DateTimeKind.Local).ToUniversalTime();
}
//The clean function converts the string to the correct date format
private static T Clean<T>(string s) {
s = Clean(s);
var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
return (s == "") ? default(T) : (T)Convert.ChangeType(s, type);
}
Basically my logic is: Convert the string to DateTime format (with the Clean function) then use SpeficyKind to treat it as a local date, then convert it to universal time.
Expected outcome: if the date string is "12/28/2019" I would want the output to be 2019-12-28T06:00:00Z. This works when I test the function locally. In my webjob, however, the result is always 2019-12-28T00:00:00Z
Don't use the concept of "local time" at all. Instead, use a specific time zone identifier, and the TimeZoneInfo
functions, such as ConvertTimeToUtc
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
DateTime utc = TimeZoneInfo.ConvertTimeToUtc(dateTime, tz);
For timeZoneId
:
If you are deploying to Functions on Windows, use "Central Standard Time"
, which covers both CST and CDT in the US and Canada.
If you are deploying to Functions on Linux, use "America/Chicago"
instead.
If you want to write cross-platform code, use my TimeZoneConverter
library to retreive the time zone with either identifier.