【问题标题】:Filtering by Date - Taking into Account the User's TimeZone按日期过滤 - 考虑用户的时区
【发布时间】:2013-04-16 15:58:08
【问题描述】:

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

以下是需要考虑的变量:

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

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

【问题讨论】:

    标签: c# datetime timezone


    【解决方案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);
    

    【讨论】:

    • 这就是我想要的。谢谢
    【解决方案2】:

    为什么不使用 C# 的 DateTime 类?它应该为您处理所有这些并且它具有比较功能?

    http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx

    它有多种结构,具体取决于您知道时间的准确程度。

    您可以使用 LINQ 对List 进行过滤。

    编辑:时区转换http://msdn.microsoft.com/en-us/library/bb397769.aspx

    【讨论】:

    • 这到底是如何解决 OP 关于时区的问题的?
    • 谢谢,但我已经知道很多了。我问的是如何做到这一点,而不是我需要做什么。
    猜你喜欢
    • 2019-12-06
    • 1970-01-01
    • 2015-03-16
    • 2021-09-16
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多