我有一个帖子列表,其中帖子的“DateAdded”字段已设置为UTC时间。我需要过滤特定月/年的帖子。我正在努力解决的部分是如何将当前用户的时区(包括夏令时)纳入帐户。
以下是需要考虑的变量:
List<Post> posts = ...;
TimeZoneInfo userTimeZone = ...;
int year = ...;
int month = ...;
如果有人能告诉我正确的方法,我会很感激。感谢
答案 0 :(得分:1)
为什么不使用C#的DateTime
课程?它应该为你处理这一切,它有一个比较功能?
http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx
根据您知道时间的准确程度,它有多种结构。
您可以使用LINQ对List
进行过滤。
编辑:对于时区转换http://msdn.microsoft.com/en-us/library/bb397769.aspx
答案 1 :(得分:1)
您只需将查询的DateTime
值转换为UTC,然后对其进行过滤。
// here are some posts
List<Post> posts = new List<Post>
{
new Post {DateAdded = new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc)},
new Post {DateAdded = new DateTime(2013, 2, 1, 0, 0, 0, DateTimeKind.Utc)},
new Post {DateAdded = new DateTime(2013, 2, 2, 0, 0, 0, DateTimeKind.Utc)},
new Post {DateAdded = new DateTime(2013, 3, 1, 0, 0, 0, DateTimeKind.Utc)},
new Post {DateAdded = new DateTime(2013, 3, 2, 0, 0, 0, DateTimeKind.Utc)},
new Post {DateAdded = new DateTime(2013, 3, 3, 0, 0, 0, DateTimeKind.Utc)},
};
// And the parameters you requested
TimeZoneInfo userTimeZone = TimeZoneInfo
.FindSystemTimeZoneById("Central Standard Time");
int year = 2013;
int month = 2;
// Let's get the start and end values in UTC.
DateTime startDate = new DateTime(year, month, 1);
DateTime startDateUtc = TimeZoneInfo.ConvertTimeToUtc(startDate, userTimeZone);
DateTime endDate = startDate.AddMonths(1);
DateTime endDateUtc = TimeZoneInfo.ConvertTimeToUtc(endDate, userTimeZone);
// Filter the posts to those values. Uses an inclusive start and exclusive end.
var filteredPosts = posts.Where(x => x.DateAdded >= startDateUtc &&
x.DateAdded < endDateUtc);