我有一个帖子列表,其中帖子有一个"DateAdded"字段已被设置为UTC时间。我需要过滤特定月份/年份的帖子。我正在努力的部分是我将如何考虑当前用户的时区(包括夏令时)。
以下是需要考虑的变量:
List<Post> posts = ...;
TimeZoneInfo userTimeZone = ...;
int year = ...;
int month = ...;
如果有人能告诉我做这件事的正确方法,我会很感激的。由于 您只需要将查询的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);
为什么不使用c#的DateTime
类呢?它应该为你处理所有这些,它有一个比较函数?
它有多种结构,取决于你知道的时间的精确程度。
您可以使用LINQ对List
进行过滤。
EDIT:用于时区转换http://msdn.microsoft.com/en-us/library/bb397769.aspx