尝试在 SQL Server 表中存储日期和时间时,时间与本地时区不对应。我应该怎样做才能纠正时间? 这是我使用过的代码。
public class Stage1Model
{
[Key]
public int JobID { get; set; }
public int EmpID { get; set; }
public string? CustomerName { get; set; }
public string? OrderDetails { get; set; }
public DateTime DispatchDate { get; set; }
public DateTime CreateDateTime { get; set; }// this is where I take time for sql
public string S1Status { get; set; }
}
这是我的模型
[EnableCors("AllowAll")]
[ApiController]
[Route("[controller]")]
public class OrderTrackingController : ControllerBase
{
private readonly ITracking _tracking;
public OrderTrackingController( ITracking tracking)
{
_tracking = tracking;
}
[HttpPost]
public async Task<IActionResult> AddEntity([FromBody] Stage1Model model)
{
if (model == null)
{
return BadRequest("Invalid data");
}
model.CreateDateTime = DateTime.UtcNow;
await _tracking.AddEntity(model);
// Return the model with CreateDateTime converted to local time
model.CreateDateTime = model.CreateDateTime.ToLocalTime();
return Ok(model);
//return CreatedAtAction(nameof(GetEntityById), new { id = model.Id }, model);
}
}`
这是我的 Controller 响应体 下载
{
"jobID": 5,
"empID": 12,
"customerName": "hello",
"orderDetails": "pan",
"dispatchDate": "2023-11-23T06:49:03.367Z",
"createDateTime": "2023-11-23T12:19:29.2882111+05:30",
"s1Status": "completed"
}
Response headers
content-type: application/json; charset=utf-8
date: Thu,23 Nov 2023 06:49:29 GMT
server: Kestrel
这是我的 API 结果,其中时间取自 SQL Server 表中响应 header 的“日期:2023 年 11 月 23 日星期四 06:49:29”GMT,但我的预期时间在响应正文中为“createDateTime”:“2023-11-23T12:19:29.2882111+05:30”,SQL Server 未考虑该信息。
最佳答案
为避免因本地时区差异而引起的困惑,请在数据库中以 UTC 格式存储日期和时间。当需要向用户显示时间时,请在应用程序级别将UTC时间转换为本地时区。这就是您在调用 ToLocalTime()
时在 Controller 中执行的操作。但是,这种转换通常应该在检索数据以供显示时完成,而不是在存储之前或将其添加到数据库之后完成。
您可以尝试以下修改后的代码:
public class Stage1Model
{
public DateTimeOffset DispatchDate { get; set; }
public DateTimeOffset CreateDateTime { get; set; }
}
Controller :
[HttpPost]
public async Task<IActionResult> AddEntity([FromBody] Stage1Model model)
{
if (model == null)
{
return BadRequest("Invalid data");
}
// Set the CreateDateTime with the current UTC time and the local offset
model.CreateDateTime = DateTimeOffset.UtcNow;
await _tracking.AddEntity(model);
// No need to convert CreateDateTime to local time here,
// since DateTimeOffset keeps track of the time zone.
return Ok(model);
}
在 SQL Server 表中,检查它是否具有使用 datetimeoffset
数据类型定义的列来适应这一点。当您从数据库读取 DateTimeOffset
并将其显示给用户时,您应该将其转换为用户的本地时区。这种转换应该在应用程序级别完成,通常是在应用程序的表示逻辑中。
关于reactjs - SQL Server 中的时区不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77534862/