C# 取得上月月頭和月尾、上週的第一天和最後一天。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WL.Infrastructure.Commom
{
    public class Time
    {
        /// 取得某月的第一天
        /// </summary>
        /// <param name="datetime">要取得月份第一天的時間</param>
        /// <returns></returns>
        private DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /// <summary>
        /// 取得某月的最後一天
        /// </summary>
        /// <param name="datetime">要取得月份最後一天的時間</param>
        /// <returns></returns>
        private DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }

        /// <summary>
        /// 取得上個月第一天
        /// </summary>
        /// <param name="datetime">要取得上個月第一天的當前時間</param>
        /// <returns></returns>
        public DateTime FirstDayOfPreviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(-1);
        }

        /// <summary>
        /// 取得上個月的最後一天
        /// </summary>
        /// <param name="datetime">要取得上個月最後一天的當前時間</param>
        /// <returns></returns>
        public DateTime LastDayOfPrdviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddDays(-1);
        }

        /// <summary>
        /// 取得上週的第一天
        /// </summary>
        /// <param name="datetime">要取得上週最後一天的當前時間</param>
        /// <returns></returns>
        public static DateTime FirstDayOfPrdviousWeek(DateTime datetime)
        {
            //星期一爲第一天  
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);

            //由於是以星期一爲第一天,因此要判斷weeknow等於0時,要向前推6天。  
            weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
            int daydiff = (-1) * weeknow;

            //本週第一天  
            string FirstDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(FirstDay);
        }

        /// <summary>
        /// 取得上週的最後一天
        /// </summary>
        /// <param name="datetime">要取得上週最後一天的當前時間</param>
        /// <returns></returns>
        public static DateTime LastDayOfPrdviousWeek(DateTime datetime)
        {
            //星期天爲最後一天  
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);
            weeknow = (weeknow == 0 ? 7 : weeknow);
            int daydiff = (7 - weeknow);

            //本週最後一天  
            string LastDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(LastDay);
        }
    }
}
相關文章
相關標籤/搜索