DateTime.TryParseExact方法用于字符串比较。

5

你好,如何在给定日期中进行字符串比较?DateTime.TryParseExact似乎是一个明智的选择,但我不确定如何构建下面方法中的参数:

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

可能是重复的问题,参考链接:http://stackoverflow.com/questions/11660423/string-comparison-on-date-format-wont-work - MikeKulls
对于使用LINQ查询语法的人而言,以下是一个有用的参考链接:https://dev59.com/NGox5IYBdhLWcg3wvWwy - Colin Smith
2个回答

13

如果你确切地知道日期/时间的格式(即它永远不会改变,并且不依赖用户的文化或区域设置),那么可以使用 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.
}

格式化字符串可以是完全指定的自定义日期/时间格式(例如dd-MM-yyyy),也可以是通用格式说明符(例如g)。对于后者,日期的格式取决于文化背景。例如,在荷兰,日期写作26-07-2012dd-MM-yyyy),而在美国,日期写作7/26/2012M/d/yyyy)。
然而,这只适用于您的字符串str仅包含要解析的日期。如果您有一个更大的字符串,其中包含各种不需要的字符和日期,那么您首先必须找到该日期。这可以使用正则表达式完成,这是另一个完整的主题。关于C#中正则表达式(regex)的一些常规信息可以在此处找到。正则表达式参考资料在此处。例如,类似于d/M/yyyy的日期可以使用正则表达式\d{1,2}\/\d{1,2}\/\d{4}找到。

0

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

以下是在 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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接