2013-04-16 21 views
0

我有一个帖子列表,其中帖子的“DateAdded”字段已被设置为UTC时间。我需要筛选特定月份/年的帖子。我挣扎的部分是我如何考虑当前用户的时区(包括夏令时)。按日期过滤 - 考虑到用户的时区

下面是需要的变量加以考虑:

List<Post> posts = ...; 
TimeZoneInfo userTimeZone = ...; 
int year = ...; 
int month = ...; 

我会很感激,如果有人可以告诉我正确的方法来做到这一点。谢谢

回答

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); 
+0

这就是我一直在寻找的。谢谢 – nfplee

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

这是如何解决OP关于时区的问题? –

+0

谢谢,但我已经知道了很多。我在问如何做,而不是我需要做什么。 – nfplee