简体   繁体   English

比较日期和可能不是日期的字符串的最佳方法是什么?

[英]What is the best way to compare a date and string that may not be a date?

I'm not sure why my head is spinning right now - long day for sure - but I need some help with this one. 我不确定为什么现在我的头在转动-当然可以漫长的一天-但是我需要一些帮助。

I have a DateTime variable and a String variable. 我有一个DateTime变量和一个String变量。 I ultimately need to compare the two for equality. 我最终需要比较两者的平等性。 The DateTime will either be null or a DateTime. DateTime将为null或DateTime。 The string will either be a date represented as a string (mm/dd/yy) or a single word. 该字符串将是一个以字符串(mm / dd / yy)表示的日期或一个单词。 A simple bool indicating the two variables are equal is all I need but I'm really struggling with this. 我只需要一个简单的布尔变量即可表明两个变量相等,但是我对此很挣扎。

At the moment, I get an error that says date2 is uninitialized. 此刻,我收到一条错误消息,指出date2未初始化。 Suggestions are much appreciated. 建议非常感激。 Thanks! 谢谢!

Here is what I started with... 这是我开始的...

string date1= "12/31/2010";
DateTime? date2= new DateTime(1990, 6, 1);

bool datesMatch = false;

DateTime outDate1;
DateTime.TryParse(date1, out outDate1);

DateTime outDate2;

if (date2.HasValue)
{
   DateTime.TryParse(date2.Value.ToShortDateString(), out outDate2);
}

if (outDate1== outDate2)
{
   datesMatch = true;
}

if (!datesMatch)
{
   // do stuff here;
}

FYI - date1 and date2 are initialized at the top for dev purposes only. 仅供参考-date1和date2仅在开发人员顶部初始化。 The actual values are pulled from a database. 实际值是从数据库中提取的。


EDIT #1 - Here is my latest. 编辑#1-这是我的最新消息。 How do I get rid of the error caused by outDate2 not being initialized? 如何摆脱未初始化outDate2引起的错误? I placed an arbitrary date in there and it clears the error. 我在其中放置了一个任意日期,它清除了错误。 It just feels wrong. 只是感觉不对。

    string date1 = "12/31/2010";
    DateTime? date2 = new DateTime(1990, 6, 1);

    bool datesMatch = false;

    DateTime outDate1;
    bool successDate1 = DateTime.TryParse(date1, out outDate1);

    DateTime outDate2;
    bool successDate2 = false;

    if (date2.HasValue)
    {
        successDate2 = DateTime.TryParse(date2.Value.ToShortDateString(), out outDate2);
    }

    if (successDate1 && successDate2)
    {
        if (outDate1 == outDate2)
        {
            datesMatch = true;
        }
    }

    if (!datesMatch)
    {
        // do stuff here;
    }

DateTime.TryParse returns a boolean, so you know whether or not it succeeded. DateTime.TryParse返回一个布尔值,因此您知道它是否成功。 Use that return value. 使用该返回值。

string date1= "12/31/2010";
DateTime? date2= new DateTime(1990, 6, 1);

bool datesMatch = false;

DateTime outDate1;
bool success = DateTime.TryParse(date1, out outDate1);

DateTime outDate2;

if (success)
{
   // etc...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM