Gets the last day of the month from the informed date and time. - CSharp System

CSharp examples for System:DateTime Month

Description

Gets the last day of the month from the informed date and time.

Demo Code


using System;/*from  ww w . j a  va  2 s.  com*/

public class Main{
        /// <summary>
        /// Gets the last day of the month from the informed date and time.
        /// </summary>
        /// <param name="dateTime">DateTime to be considered.</param>
        /// <param name="keepTime">Set it to <see cref="false"/> so the hour, minute, second and millisecond will turn to the latest time possible.</param>
        /// <returns>Returns the last day of the month from the informed date and time.</returns>
        public static DateTimeOffset LastDayOfTheMonth(this DateTimeOffset dateTime, bool keepTime = true)
        {
            int lastDayOfTheMonth = DateTime.DaysInMonth(dateTime.Year, dateTime.Month);
            DateTimeOffset newDateTime = dateTime;

            if (keepTime)
            {
                newDateTime = new DateTimeOffset(dateTime.Year, dateTime.Month, lastDayOfTheMonth,
                    dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, dateTime.Offset);
            }
            else
            {
                newDateTime = new DateTimeOffset(dateTime.Year, dateTime.Month, lastDayOfTheMonth,
                    00, 00, 00, 00, dateTime.Offset).AddDays(1).AddMilliseconds(-1);
            }

            return newDateTime;
        }
        #endregion

        #region LastDayOfTheMonth
        /// <summary>
        /// Gets the last day of the month from the informed date and time.
        /// </summary>
        /// <param name="dateTime">DateTime to be considered.</param>
        /// <param name="keepTime">Set it to <see cref="false"/> so the hour, minute, second and millisecond will turn to the latest time possible.</param>
        /// <returns>Returns the last day of the month from the informed date and time.</returns>
        public static DateTime LastDayOfTheMonth(this DateTime dateTime, bool keepTime = true)
        {
            int lastDayOfTheMonth = DateTime.DaysInMonth(dateTime.Year, dateTime.Month);
            DateTime newDateTime = dateTime;

            if (keepTime)
            {
                newDateTime = new DateTime(dateTime.Year, dateTime.Month, lastDayOfTheMonth,
                    dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, dateTime.Kind);
            }
            else
            {
                newDateTime = new DateTime(dateTime.Year, dateTime.Month, lastDayOfTheMonth,
                    00, 00, 00, 00, dateTime.Kind).AddDays(1).AddMilliseconds(-1);
            }

            return newDateTime;
        }
}

Related Tutorials