Azure webjob 将时间转换为通用时间

Azure webjob convert time to Universal time

我有一个 Azure 网络作业涉及获取字符串值并将其转换为 DateTime 值。问题是我希望函数假设这个时间最初是在中央时间 (CST) 中输入的,然后将其转换为通用时间。当我 运行 在本地运行此功能时,一切都按预期进行。我认为问题在于,当函数从 azure 服务器 运行ning 开始时,它假定所有时间都以 UTC 开始(因此尝试将其转换为 UTC 根本不会改变它)。

这是我的代码:

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);
}

基本上我的逻辑是: 将字符串转换为 DateTime 格式(使用 Clean 函数),然后使用 SpeficyKind 将其视为本地日期,然后将其转换为世界通用时间。

预期结果: 如果日期字符串是“12/28/2019”,我希望输出为 2019-12-28T06:00:00Z。当我在本地测试该功能时,这会起作用。 然而,在我的网络作业中,结果始终是 2019-12-28T00:00:00Z

Azure 应用服务使用 UTC 时区作为默认/本地时区。尝试将您应用的时区设置为 CST:http://www.louischarlesgagnon.com/post/azure-app-service-set-timezone-for-your-web-application

更新

或者,您可以使用 DateTimeOffset 而不是 DateTime

var timezone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");

var ctsDate = DateTime.Parse(date, System.Globalization.CultureInfo.InvariantCulture);
var offset = timezone.GetUtcOffset(ctsDate);

var utcDate = new DateTimeOffset(ctsDate, offset).ToUniversalTime().DateTime;

根本不要使用"local time"的概念。相反,使用特定的时区标识符和 TimeZoneInfo 函数,例如 ConvertTimeToUtc

TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
DateTime utc = TimeZoneInfo.ConvertTimeToUtc(dateTime, tz);

对于timeZoneId

  • 如果您要部署到 Windows 上的 Functions,请使用 "Central Standard Time",它涵盖美国和加拿大的 CST 和 CDT。

  • 如果要在 Linux 上部署到 Functions,请改用 "America/Chicago"

  • 如果您想编写跨平台代码,请使用我的 TimeZoneConverter 库来检索带有任一标识符的时区。