我正在使用默认示例将日期时间值存储在表存储中。一字段计算如下
DateTime accMonth = new DateTime(DateTime.Now.Year,
DateTime.Now.Month, 1);
通常上面是指时间为 00:00 的日期。
但是,当我将其保存在表存储中时,我认为这次是
2018-04-01T18:30:00.000Z
这对我来说看起来很奇怪!有谁知道为什么?
我正在使用默认示例将日期时间值存储在表存储中。一字段计算如下
DateTime accMonth = new DateTime(DateTime.Now.Year,
DateTime.Now.Month, 1);
通常上面是指时间为 00:00 的日期。
但是,当我将其保存在表存储中时,我认为这次是
2018-04-01T18:30:00.000Z
这对我来说看起来很奇怪!有谁知道为什么?
您获得了不同的值,因为您正在使用本地时区创建日期/时间(印度是 GMT+5:30)。在 Azure 存储中,日期/时间值保存为 UTC。
SDK 正在做的是将此日期转换为 UTC,然后保存该日期。这就是为什么您会在您设置的日期/时间值之前 5:30 看到一个日期/时间值。
要解决此问题,请将日期/时间类型指定为 UTC。然后 SDK 不会做任何转换。所以你的代码是:
var accMonth = new DateTime(DateTime.Now.Year,
DateTime.Now.Month, 1, 0, 0, 0, DateTimeKind.Utc);
您似乎希望将 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; }
}
屏幕截图是: