簡體   English   中英

用於字符串比較的DateTime.TryParseExact方法

[英]DateTime.TryParseExact method for string comparison

你怎么能在給定的日期做一個字符串比較匹配, DateTime.TryParseExact似乎是明智的選擇,但我不知道如何在下面的方法中構建爭論:

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

如果您確切地知道日期/時間的格式(即它永遠不會更改,並且不依賴於用戶的文化或區域設置),那么您可以使用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{1,2}\\/\\d{1,2}\\/\\d{4}找到類似於d/M/yyyy的日期。

另一種方法是將日期從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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM