0

我有一个帖子列表,其中帖子有一个“添加日期”字段,该字段已设置为 UTC 时间。我需要过滤特定月份/年份的帖子。我正在努力的部分是我将如何考虑当前用户的时区(包括夏令时)。

以下是需要考虑的变量:

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

如果有人能告诉我正确的方法,我将不胜感激。谢谢

4

2 回答 2

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

于 2013-04-16T16:12:37.370 回答
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);
于 2013-04-16T16:43:29.777 回答