【问题标题】:DateTime.TryParseExact method for string comparison字符串比较的 DateTime.TryParseExact 方法
【发布时间】:2012-07-26 00:26:50
【问题描述】:

嘿,如何为给定日期进行字符串比较匹配,DateTime.TryParseExact 似乎是明智的选择,但我不确定如何在以下方法中构建争论:

public List<Dates> DateEqualToThisDate(string dateentered)
{
    List<Dates> date = dates.Where(
        n => string.Equals(n.DateAdded, 
                           dateentered,
                           StringComparison.CurrentCultureIgnoreCase)).ToList();
        return hiredate;
 }

【问题讨论】:

标签: c# linq


【解决方案1】:

如果您确切知道日期/时间的格式(即它永远不会改变,并且不依赖于用户的文化或区域设置),那么您可以使用DateTime.TryParseExact

例如:

DateTime result;
if (DateTime.TryParseExact(
    str,                            // The string you want to parse
    "dd-MM-yyyy",                   // The format of the string you want to parse.
    CultureInfo.InvariantCulture,   // The culture that was used
                                    // to create the date/time notation
    DateTimeStyles.None,            // Extra flags that control what assumptions
                                    // the parser can make, and where whitespace
                                    // may occur that is ignored.
    out result))                    // Where the parsed result is stored.
{
    // Only when the method returns true did the parsing succeed.
    // Therefore it is in an if-statement and at this point
    // 'result' contains a valid DateTime.
}

格式字符串可以是完全指定的custom date/time format(如dd-MM-yyyy)或general format specifier(如g)。对于后者,文化对于日期的格式很重要。例如,在荷兰,日期写为 26-07-2012 (dd-MM-yyyy),而在美国,日期写为 7/26/2012 (M/d/yyyy)。

但是,这一切仅在您的字符串 str 仅包含您要解析的日期时才有效。如果您有一个较大的字符串,并且日期周围有各种不需要的字符,那么您必须首先在其中找到日期。这可以使用正则表达式来完成,这本身就是另一个主题。可以在here 找到有关 C# 中的正则表达式 (regex) 的一些一般信息。正则表达式引用是here。例如,可以使用正则表达式 \d{1,2}\/\d{1,2}\/\d{4} 找到类似于 d/M/yyyy 的日期。

【讨论】:

    【解决方案2】:

    另一种方法是将日期从string 转换为DateTime。如果可能的话,我会将DateAdded 保留为DateTime

    Bellow 是在 LINQPad 中运行的代码

    public class Dates
    {
        public string DateAdded { get; set; }
    }
    
    List<Dates> dates = new List<Dates> {new Dates {DateAdded = "7/24/2012"}, new Dates {DateAdded = "7/25/2012"}};
    
    void Main()
    {
        DateEqualToThisDate("7/25/2012").Dump();
    }
    
    public List<Dates> DateEqualToThisDate(string anything)
    {
        var dateToCompare = DateTime.Parse(anything);
    
        List<Dates> hireDates = dates.Where(n => DateTime.Parse(n.DateAdded) == dateToCompare).ToList();
    
        return hireDates;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多