In an object of type DateTime
, how do I get a new object object DateTime
that represents the last day of the month of the first object?
var data = new Date(2017, 3, 1); // 01/03/2017
var dataUltimoDia = ??? // 31/03/2017
In an object of type DateTime
, how do I get a new object object DateTime
that represents the last day of the month of the first object?
var data = new Date(2017, 3, 1); // 01/03/2017
var dataUltimoDia = ??? // 31/03/2017
You can use the FluentDateTime package. It provides the LastDayOfMonth()
extension method plus a number of other extremely useful extensions.
You can install it through nuget
PM > install-package FluentDateTime
Use
using FluentDateTime;
...
DateTime ultimoDiaDoMes = qualquerData.LastDayOfMonth();
And you can also do it in a way (which I think) simpler than this in your answer
var qualquerData = new DateTime(data.Year, data.Month, 1);
DateTime ultimoDiaDoMes = qualquerData.AddMonths(1).AddDays(-1);
To get the day only, the DaysInMonth method that receives as parameters the month and the year and will return a int
which will be the last day.
With the last day retrieved, I created a new object of type DateTime
using the month and year of my original object plus the day retrieved.
var data = new DateTime(2015, 11, 7);
var ultimoDia = DateTime.DaysInMonth(data.Year, data.Month);
var dataUltimoDia = new DateTime(data.Year, data.Month, ultimoDia);
How do I find out the last day of this month?
var ultimoDia = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);