C# 根据当前时间获取本周、本月、本季度、本年的始末日期

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


namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            GetTimes(PeriodType.Day);
            GetTimes(PeriodType.Week);
            GetTimes(PeriodType.Month);
            GetTimes(PeriodType.Quarter);
            GetTimes(PeriodType.Year);
            Console.ReadLine();
        }
        /// <summary>
        /// C# 根据当前时间获取本周、本月、本季度、本年的始末日期。
        /// </summary>
        /// <param name="type"></param>
        private static void GetTimes(PeriodType type)
        {
            DateTime startTime;
            DateTime endTime;
            DateTime nowTime = DateTime.Now.Date;
            switch (type)
            { 
                case PeriodType.Day://本日
                    startTime = DateTime.Now.Date;
                    endTime = DateTime.Now.Date;
                    break;
                case PeriodType.Week://本周以星期天为第一天
                    startTime = nowTime.AddDays(0 - Convert.ToInt32(nowTime.DayOfWeek));
                    endTime = startTime.AddDays(6);
                    break;
                case PeriodType.Month://本月
                    startTime = nowTime.AddDays(1 - nowTime.Day);
                    endTime = startTime.AddMonths(1).AddDays(-1);
                    break;
                case PeriodType.Quarter://本季度
                    startTime = nowTime.AddMonths(0 - (nowTime.Month - 1) % 3).AddDays(1 - nowTime.Day);
                    endTime = startTime.AddMonths(3).AddDays(-1);
                    break;
                case PeriodType.Year://本年
                    startTime = new DateTime(nowTime.Year, 1, 1);
                    endTime = new DateTime(nowTime.Year, 12, 31);
                    break;
                default://本日
                    startTime=DateTime.Now.Date;
                    endTime = DateTime.Now.Date;
                    break;
            }
            Console.WriteLine("{0}: {1}—{2}", type, startTime.ToString("yyyy-MM-dd"), endTime.Date.ToString("yyyy-MM-dd"));
        }
        private enum PeriodType
        {
            Day,
            Week,
            Month,
            Quarter,
            Year
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值