如何为 ASP.NET Core API 启用时区支持?

How to enable Time Zone support for ASP.NET Core API?

我有一个移动应用程序和一个 Web 应用程序,它们使用 ASP.NET 核心 3.x WEB API,使用 SQL 服务器作为数据存储。客户端应用程序可以在不同的时区。

我面临的困境是过滤具有日期范围的记录。

例如,我有一个名为 'PaymentTransaction' 的 table,它由类型为 DateTimeOffset.

的列 'TransactionDateTime' 组成

实体对象:

[Table("PaymentTransaction")]
public class PaymentTransaction 
{
    public DateTimeOffset TransactionDateTime { get; set; }
}

API 用于创建记录的端点:PaymentRequestDto 为简洁起见排除的内容

[HttpPost, Route("Create")]
public async Task<ActionResult> Create([Required] PaymentRequestDto)
{
    await _context.PayoutTransactions.AddAsync(new PaymentTransaction()
    {
        TransactionDateTime = DateTimeOffset.UtcNow;
    });

    await _context.SaveChangesAsync();    
    return Ok();
}

API 用于过滤记录的端点:

[HttpGet, Route("GetRangeSample/{startDateTime}/{endDateTime}")]
public async Task<ActionResult> GetRangeSample([Required] DateTimeOffset startDateTime, [Required] DateTimeOffset endDateTime)
{
    var result = await _context.PaymentTransactions.Where(x => x.TransactionDateTime >= date && x.TransactionDateTime <= date).ToListAsync();
    return Ok(result);
}

JavaScript 客户端请求过滤记录;

var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getDate() + 7)

$.ajax({
    type: "get",
    url: "http://localhost:55724/api/GetRangeSample",
    data:{
        startDateTime: startDate,
        endDateTime: endDate
    },
    success: function(response){
        console.log(response);
    },
    error: function(error)
    {
        console.log(error);
    }
});

如果我要过滤给定日期范围内的记录,假设 02-21-202202-28-2022。部分记录未返回。

我做错了什么?您通常如何根据日期过滤器保存 DateTimeOffset 和检索记录?

假设您的意思是让用户 select 一整天都在 他们的 时区,问题在于您创建开始日期和结束日期的方式您的 JavaScript 代码。请记住,JavaScript Date 对象表示一个时间点( 不是 整个日期),而 new Date() 给出了时间点即现在.

因此,您可能应该像这样创建开始日期和结束日期,这样它们就包含了整整一天,而不是仅包含 运行 代码之后的剩余时间。

var startDate = new Date();   // get the current "now"
startDate.setHours(0,0,0,0);  // adjust to the start of the local day
var endDate = new Date(startDate);      // copy to another instance
endDate.setDate(endDate.getDate() + 7); // advance 7 days