【问题标题】:Storing DateTime in azure table storage将日期时间存储在天蓝色表存储中
【发布时间】:2018-04-26 08:47:17
【问题描述】:

我正在使用默认示例将日期时间值存储在表存储中。一字段计算如下

DateTime accMonth = new DateTime(DateTime.Now.Year, 
    DateTime.Now.Month, 1);

上面通常表示时间为 00:00 的日期。

但是,当我将其保存在表存储中时,我认为这次是

2018-04-01T18:30:00.000Z

这对我来说很奇怪!谁知道为什么?

【问题讨论】:

  • 这只是一个猜测,但可能与您当地的时区有关。这是我在日期时间不匹配的情况下首先要查找的地方。
  • 你在哪里运行这段代码?我是从你的本地机器上猜测的。
  • 另外,你确定它显示为2018-04-01T18:30:00.000Z而不是2018-03-31T18:30:00.000Z
  • 代表@Mike Hjort Christensen - Can you show the code where you store accMonth?
  • 这绝对看起来像是 UTC 问题。确保 accMonth 的 Kind 是 DateTimeKind.Utc。

标签: c# azure azure-storage azure-table-storage


【解决方案1】:

您获得了不同的值,因为您正在使用本地时区创建日期/时间(印度是 GMT+5:30)。在 Azure 存储中,日期/时间值保存为 UTC。

SDK 所做的是将此日期转换为 UTC,然后保存该日期。这就是为什么您会看到比您设置的日期/时间值早 5:30 小时的日期/时间值。

Edm.DateTime under Property Types

要解决此问题,请将日期/时间类型指定为 UTC。然后 SDK 不会做任何转换。所以你的代码是:

var accMonth = new DateTime(DateTime.Now.Year, 
            DateTime.Now.Month, 1, 0, 0, 0, DateTimeKind.Utc);

【讨论】:

  • @Mike Hjort Christensen - 感谢您的编辑。您不能发表评论,但允许编辑帖子,这不是很奇怪吗? :)
  • 抱歉回复晚了,但这是否意味着表存储中的所有日期都以 UTC 格式存储,没有任何时区,所以您总是需要转换为本地时区?
【解决方案2】:

您似乎想将 DateTime 格式化为: yyyy-MM-dd 00:00:00

如果是这样,你可以使用下面的代码来实现:

DateTime accMonth = new DateTime(DateTime.Now.Year,DateTime.Now.Month, 1);
string formatted = accMonth.ToLongTimeString();
double hour = DateTime.Now.Hour;
customer1.date = Convert.ToDateTime(formatted).AddHours(-hour+1);

完整代码如下:

private static void Main()
{
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

    CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

    CloudTable table = tableClient.GetTableReference("people");

    CustomerEntity customer1 = new CustomerEntity("Harp1", "Walter1");

    DateTime accMonth = new DateTime(DateTime.Now.Year,DateTime.Now.Month, 1);
    string formatted = accMonth.ToLongTimeString();
    double hour = DateTime.Now.Hour;
    customer1.date = Convert.ToDateTime(formatted).AddHours(-hour+1);

    TableOperation insertOperation = TableOperation.Insert(customer1);

    table.Execute(insertOperation);
}

public class CustomerEntity : TableEntity
{
    public CustomerEntity(string lastName, string firstName)
    {
        this.PartitionKey = lastName;
        this.RowKey = firstName;
    }

    public CustomerEntity() { }

    public DateTime date { get; set; }
}

屏幕截图是:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 2013-11-08
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多