Click here to Skip to main content
15,904,926 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to compare dates in yyyyMM format in c#. I will get a date in the mentioned format(eg:202104) and i need to compare it with the current date with similar format. Since it is not a datetime value how to compare the same.

What I have tried:

datetime comparison is known. but how to manage dates with yyyyMM format
Posted
Updated 31-May-21 20:50pm
v2

Comparing dates in a specific format does not make sense, dates are dates. If you want to check that part of the date matches you can use the properties of the datetime to extract the desired portion.

For example, if you need to see that year and month for specific dates match, you can use DateTime.Year Property (System) | Microsoft Docs[^] and DateTime.Month Property (System) | Microsoft Docs[^] correspondingly.
 
Share this answer
 
Convert it to a DateTime object using DateTime.TryParseExact[^] and compare the two results:
C#
string inp = "202104";
DateTime dt;
if (!DateTime.TryParseExact(inp, "yyyyMM", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
    {
    ... Report problem with date value ...
    return;
    }
 
Share this answer
 
Quote:
datetime comparison is known. but how to manage dates with yyyyMM format

Directly, because it is yyyyMM (in this order), you can directly compare the 2 values.
DateTimes are stored in format yyyyMMDD, dropping the days do not change anything.
C#
string dt1= "202104"
string dt2= "202106"
if (dt1 < dt2) {
  // dt1 is older
}

The problem when you have as MMyyyy format.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900