Home > OS >  Compare YYYYmm string with DateTime in C#
Compare YYYYmm string with DateTime in C#

Time:06-16

I have YYYYmm string and i want to compare datetime.

(MyDateTimeDate.Year == int.Parse(MyStringDate.Substring(0, 4))) &&
(MyDateTimeDate.Month > int.Parse(MyStringDate.Substring(MyStringDate.Length - 2)) ||
MyDateTimeDate.Year > int.Parse(MyStringDate.Substring(0, 4)));

I tried this method, but I did not get the correct result and the process took too long.

I'm trying to add the value 01 to the string and convert it to datetime and compare, but how to do it? Is it true logic?

CodePudding user response:

You can parse MyStringDate to DateTime with year and month i.e yyyyMM, Parsing will add default day as 1, you need not to add 01 to string

var dt = DateTime.ParseExact(myStringDate, "yyyyMM", CultureInfo.InvariantCulture);

Now you can check the condition,

(MyDateTimeDate.Year == dt.Year && 
  (MyDateTimeDate.Month > dt.Month || MyDateTimeDate.Year> dt.Year)

CodePudding user response:

As you suggested, to get the benefits of DateTime built-in comparison mecanisms, you should first convert both "dates" to a DateTime object that does not contain problematic day information.

First, you can easily convert the string in this way:

var stringDate = "202207"; // An example.
var myParsedTimeDate = DateTime.ParseExact(stringDate, "yyyyMM", null); // Gives 01/07/2022 00:00:00

The set your other date day to 1:

var myDateTimeDateYearMonthOnly = new DateTime(myDateTimeDate.Year, myDateTimeDate.Month, 1); // Will set the date to the first of the month.

You can then use any comparison between the two date in a readable form:


if (myParsedTimeDate > myDateTimeDateYearMonthOnly)
{
    // Do whatever.
}

// Or

if (myParsedTimeDate == myDateTimeDateYearMonthOnly)
{
    // Do whatever.
}

// Etc... same princple for >=, <=, <
  • Related