Find date (end of month) from month and year from string?

Find date (end of month) from month and year from string.
Example : I have variable month as string = 05 and variable year as string =2021

I want output = 31 (Last date in May 2021)

Please guide me about it.

Hi @fairymemay ,

Try this

CDate(“05/01/2021”).AddMonths(1).AddDays(-1).ToString

I have hardcoded date but you can pass the variable to date

You can also use it as

DateTime.Parse(“08/01/2021”).AddMonths(1).AddDays(-1).ToString

Hi.

Colleague of mine had developed wonderful and easy system how to do it.

Take this date, add one month, take first date of newly determined date and substract one date.

Below example (please, bear in mind that below below example counts with dd.MM.yyyy convention, this is why you have there ParseExact and in order to make ParseExact work, you need to Import System.Globalization:
DateTime.ParseExact((“01.” + now.Month.ToString(“00”) + “.” + now.Year.ToString), “dd.MM.yyyy”, CultureInfo.CurrentCulture).AddDays(-1).ToString(“dd.MM.yyyy”)

If you got basic idea, you can construct your expression. Once you have it in DateTime, then you can use .Day to output date number (Integer, .ToString to convert it to string).

Hope this help.


Try this for getting count of days of month

variable type should be int

@fairymemay

1 Like

Hi,

Can you try the following expression?

DateTime.DaysInMonth(Int32.Parse(strYear),Int32.Parse(strMonth))

This returns 31 as Int32 type.

Regards,

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.