Taking 2 Previous Month Last Day

Hi guys, i have a problem with taking last 2 month last day. I tried some codes but didn’t work.

I tried this code

=> Now.AddDays(-Now.Day).AddMonths(-1).ToString(“dd.MM.yyyy”)
output : “30.08.2023” and its wrong, it should had been 31.08.2023

how can i get last day of 2 months past?

Thank you.

Hi @Kuki_Force

Try this

Now.AddMonths(-2).AddMonths(1).AddDays(-Now.AddMonths(-2).AddMonths(1).Day).ToString("dd.MM.yyyy")

1 Like

@Kuki_Force

1 Like

HI @Kuki_Force

Try with this expression

New DateTime(Now.Year,Now.AddMonths(-1).Month,1).AddDays(-1).ToString("dd/MM/yyyy")

image

1 Like

Hi @Kuki_Force

Try this:

twoMonthsAgo = DateTime.Now.AddMonths(-2)

lastDayOfTwoMonthsAgo = (new DateTime(twoMonthsAgo.Year, twoMonthsAgo.Month, DateTime.DaysInMonth(twoMonthsAgo.Year, twoMonthsAgo.Month))).ToString("dd.MM.yyyy")

or
str_lastDayOfTwoMonthsAgo = (DateTime.Now.AddMonths(-2).AddMonths(1).AddDays(-DateTime.Now.AddMonths(-2).AddMonths(1).Day)).ToString("dd.MM.yyyy")

1 Like

@supriya117 @lrtetala @Gokul001

Thank you guys all codes are fine.

Thanks for help.

Best wishes :innocent:

2 Likes

Can you explain the code for understanding the logic if it is possible for you ?

@Kuki_Force

Let’s go with step by step

  1. Now.AddMonths(-2) subtracts 2 months from the current date.
  2. .AddMonths(1) adds 1 month to the result, so you’re now at the first day of the next month.
  3. .AddDays(-Now.AddMonths(-2).AddMonths(1).Day) subtracts the day of the month from the result to get the last day of the previous month.
  4. .ToString("dd.MM.yyyy") formats the date as “dd.MM.yyyy.”
1 Like

If i going to change the month, i should change the Now.Add.Months(-1) for the last month right
and if i’m going to change the day for example; getting first day of last month or 2 previous month what should i change?

@Kuki_Force

  • To get the first day of the last month, you can use Now.AddMonths(-1).AddDays(-Now.Day + 1). This subtracts one month from the current date and then subtracts the current day of the month and adds 1 to get the first day of the last month.
  • To get the first day of two months ago, use Now.AddMonths(-2).AddDays(-Now.Day + 1). This subtracts two months from the current date and then subtracts the current day of the month and adds 1 to get the first day of two months ago.
1 Like

I got it bro. Thanks for explanation :innocent:

1 Like

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