我正在开发一个在Azure上托管的后端API,我的日期又回到了不同的时区。我目前获取日期的方式是使用我的迁移文件夹中的自定义Up()
方法,该方法与此类似:
public partial class MyMigration : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Users",
c => new
{
Created = c.DateTime(nullable: false, defaultValueSql: "GETDATE()"),
})
.PrimaryKey(t => t.ID);
... //
我一直在阅读sysdatetimeoffset()
和datetimeoffset()
,但我不知道如何在这种背景下使用它们。
有没有办法使用Entity Framework代码优先迁移设置数据库生成的默认DateTime和偏移量?
答案 0 :(得分:1)
Azure时间(SQL,Web应用程序,云服务)始终处于UTC时间。如果您希望API返回特定时区的时间,最好使用.NET资源将UTC时间转换为您感兴趣的时区,并让Azure处理/存储UTC时间。请参阅MSDN上的Converting Times Between Time Zones,特别是Converting UTC to a Designated Time Zone部分:
DateTime timeUtc = DateTime.UtcNow;
try
{
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
Console.WriteLine("The date and time are {0} {1}.",
cstTime,
cstZone.IsDaylightSavingTime(cstTime) ?
cstZone.DaylightName : cstZone.StandardName);
}
catch (TimeZoneNotFoundException)
{
Console.WriteLine("The registry does not define the Central Standard Time zone.");
}
catch (InvalidTimeZoneException)
{
Console.WriteLine("Registry data on the Central Standard Time zone has been corrupted.");
}