How to create a Datetime object that represents the last day of a given month?

Asked

Viewed 7,644 times

12

On an object of the type DateTime, how do I get a new object object DateTime representing 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

3 answers

13


You can use the package Fluentdatetime. It provides the extension method LastDayOfMonth() in addition to a number of other extremely useful extensions.

You can install it by 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);
  • Great package this. In my case now I can not use third party packages, but I will remember it in my projects.

10

I found that answer in Soen

To get only the day there is the method Daysinmonth which receives as parameters the month and the year and will return a int that will be the last day.

With the last day recovered, I created a new object of the type DateTime using the month and year of my original object plus the day recovered.

var data = new DateTime(2015, 11, 7);
var ultimoDia = DateTime.DaysInMonth(data.Year, data.Month);
var dataUltimoDia = new DateTime(data.Year, data.Month, ultimoDia);
  • They may even speak bad of the php language, but in it this operation would be done in only one line ;)

  • I can do on a line @Wallacemaxters :P

  • @Wallacemaxters I haven’t played with PHP for a long time, but PHP doesn’t have As far as I know, and Ingles is everything! :)

  • DateTime ultimoDiaDoMes = qualquerData.AddMonths(1).AddDays(-1); @Wallacemaxters :P

  • @jbueno so will work only if qualquerData is the first day of the month. xD

  • Lol true @Pedrocamarajunior. Two lines then :P

  • 1

    @Pedrocamarajunior if link is what we call chainability then we can do yes in php (new DateTime('last day of mouth'))->setTime(0, 0, 0)->format()

Show 2 more comments

5

how do I find out the last day of this month?

var ultimoDia = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);

Browser other questions tagged

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