Datetimepicker, get first and last day of the month

Asked

Viewed 3,293 times

2

How do I take the first and last day of the previous month, to fill a DateTimePicker on screen?

Ex:

Data Inicial 01/07/2015
Data Final   31/07/2015
  • 5

    Post what you’ve tried to do.

  • You want to do something specifically in control DateTimePicker or just want to have this information on any date? Put what you did, explain better where you want to get, what result you want.

2 answers

2


The question is not very clear but it must be something like this:

var data = picker.Value; //pega a data que está no controle
var mesAnterior = data.AddMonths(-1);
var primeiroDia = new DateTime(mesAnterior.Year, mesAnterior.Month, 1); 
var ultimoDia =  new DateTime(mesAnterior.Year, mesAnterior.Month,
        DateTime.DaysInMonth(mesAnterior.Year, mesAnterior.Month));

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

There are countless other formulas for doing this. Each may have an advantage over the other but in general it will make little or no difference in simple things. I did a test below using extension methods, so you can use it as part of the type.

  • 2

    Thank you very much It worked perfectly .

0

There is an answer here

See if that helps you too:

DateTime dtUltimoDiaMes = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1);

Remember this. The last day of the previous month is the primeiro_dia_mês_corrente menos_um_dia(AddDays(-1)). This is the formula.

  • 1

    "Can anyone tell me how to take the first day and the last day of the previous month ?"

  • 1

    I was just pointing out that the code calculates the last day of the current month, while the question asks the last day of the previous month. A small (but important) detail.

  • @dcastro, I get it, but if you look at the code I posted, it takes a certain month and comes back one day, which will be the last day of the previous month. I think that’s what he asked for, from what I read.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.