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

CSharp examples for System:DateTime Month

Description

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

Demo Code


using System;/* w  ww.  j  av  a 2s. co m*/

public class Main{
        /// <summary>
        /// Gets the first 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 zero.</param>
        /// <returns>Returns the first day of the month from the informed date and time.</returns>
        public static DateTimeOffset FirstDayOfTheMonth(this DateTimeOffset dateTime, bool keepTime = true)
        {
            DateTimeOffset newDateTime = dateTime;

            if (keepTime)
            {
                newDateTime = new DateTimeOffset(dateTime.Year, dateTime.Month, 01,
                    dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, dateTime.Offset);
            }
            else
            {
                newDateTime = new DateTimeOffset(dateTime.Year, dateTime.Month, 01,
                    00, 00, 00, 00, dateTime.Offset);
            }

            return newDateTime;
        }
        #region FirstDayOfTheMonth
        /// <summary>
        /// Gets the first 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 zero.</param>
        /// <returns>Returns the first day of the month from the informed date and time.</returns>
        public static DateTime FirstDayOfTheMonth(this DateTime dateTime, bool keepTime = true)
        {
            DateTime newDateTime = dateTime;

            if (keepTime)
            {
                newDateTime = new DateTime(dateTime.Year, dateTime.Month, 01,
                    dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, dateTime.Kind);
            }
            else
            {
                newDateTime = new DateTime(dateTime.Year, dateTime.Month, 01,
                    00, 00, 00, 00, dateTime.Kind);
            }

            return newDateTime;
        }
}

Related Tutorials