有没有什么办法可以阻止mongodb c#驱动程序将过滤器查询中传递的任何日期转换为UTC,而不是接受UTC?
我正在使用带有一些telerik控件的.net核心2.1来显示网格。在网格的标题中,我有一个过滤器控件来过滤日期范围。
在过滤之前,在客户端事件中,我捕获日期并将其转换为utc:
function onGridFilter(e) {
// check if it is a date field
if (e.filter && e.field === "created"){
convertDateToUTC(e.filter);
}
}
function convertDateToUTC(filter) {
var filters = filter.filters;
for (var i = 0; i < filters.length; i++) {
if (filters[i].field === "created") {
var date = filters[i].value;
var isoDate = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
filter.filters[i].value = isoDate;
}
}
}
在API调用中,我将UTC日期转换为服务器的本地时间,如下所示(此API是kubernetes微服务,可以具有不同的时区,具体取决于它的部署位置):
// Update the dates to server times for filtering, mongo will accept dates and convert to UTC based on the server location
foreach (var f in this.Filters)
{
if (f.ConvertedValue.GetType() == typeof(DateTime))
{
DateTime dt = (DateTime)f.Value;
f.Value = dt.ToLocalTime();
}
}
使用telerik过滤器(DataSourceRequest对象)和mongodb c#驱动程序(linq to mongo),我创建了一个mongo查询来过滤mongo数据库中的记录。
public DataSourceResult GetCollectionQuery(string organizationId, DataSourceRequest request)
{
IMongoCollection<Case> casesCollection = _db.GetCollection<Case>(_collection);
IMongoCollection<Person> personCollection = _db.GetCollection<Person>(_personCollection);
IQueryable<CaseListViewModel> query;
// Setup full results query
query = (from c in casesCollection.AsQueryable()
where c.OrganizationId == organizationId
join p in personCollection.AsQueryable() on c.ClientId equals p.Id into p
from person in p.DefaultIfEmpty()
select new CaseListViewModel()
{
Id = c.Id,
DisplayName = person != null ? person.LastName + ", " + person.FirstName : string.Empty,
OrganizationCaseId = c.OrganizationCaseId,
ServiceName = c.ServiceName,
ClientType = c.ClientType,
Addresses = c.ClientTypeValue == ClientTypeValue.Person ? person.Addresses != null ?
person.Addresses.Where(o => !o.End.HasValue).Select(o => o.AddressLine1) : null : null,
Worker = string.Empty, //c.Assignments,
Created = c.Created,
Status = c.Status,
OrganizationGeography = person != null ? person.OrganizationGeography != null ? person.OrganizationGeography.Name : string.Empty : string.Empty
});
// Filter/Sort/Page results
return query.ToDataSourceResult(request);
}
我将客户端转换为UTC,将UTC转换为服务器,然后将日期传递给mongo查询的原因是因为客户端和服务器可以位于不同的时区。
这似乎是很多不必要的工作来过滤网格上的日期。目前这个解决方案确实有效,但我正在寻找mongodb c#驱动程序端的替代方案。我希望mongodb查询将所有日期读取为UTC,而不是将检索到的日期转换为UTC。
我知道有一种方法可以告诉属性它正通过BsonDateTimeOptions DateTimeKind保存为utc:
[BsonElement(elementName: "created")]
[BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
public DateTime Created { get; set; }
对于查询也有类似的东西吗?
更新:解决方案是指定被过滤日期的DateTimeKind。
foreach (var f in this.Filters)
{
if (f.ConvertedValue.GetType() == typeof(DateTime))
{
DateTime dt = (DateTime)f.Value;
dt = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
f.Value = dt;
}
}
https://stackoverflow.com/questions/52837291
复制相似问题