Storing DateTime in azure table storage

浪子不回头ぞ 提交于 2019-12-08 11:21:11

问题


I am using default example for storing a datetime value in table storage. One the field is calculated as follows

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

Usually above means a date with time being 00:00 .

However when I save this in table storage I see this time as

2018-04-01T18:30:00.000Z

Which looks strange to me! anyone knows why?


回答1:


You're getting a different value because you're creating a date/time with local time zone (India is GMT+5:30). In Azure Storage, date/time values are saved as UTC.

What the SDK is doing is converting this date into UTC and then saving that date. That's why you're seeing a date/time value 5:30 hours before the date/time value you're setting.

Edm.DateTime under Property Types

To solve this problem, specify the date/time kind as UTC. Then the SDK will not do any conversion. So your code would be:

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



回答2:


It seems that you want to format the DateTime as this: yyyy-MM-dd 00:00:00

If so, you could use the following code to achieve:

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

The complete code is as below:

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

The screen shot is:



来源:https://stackoverflow.com/questions/50038661/storing-datetime-in-azure-table-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!