C#获取周的第一天、最后一天、月第一天和最后一天

[csharp] view plaincopyprint?

    public class DateTimeTool
{
/// <summary>
/// 获取指定日期所在周的第一天,星期天为第一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime GetDateTimeWeekFirstDaySun(DateTime dateTime)
{
DateTime firstWeekDay = DateTime.Now; try
{
//得到是星期几,然后从当前日期减去相应天数
int weeknow = Convert.ToInt32(dateTime.DayOfWeek); int daydiff = (-) * weeknow; firstWeekDay = dateTime.AddDays(daydiff);
}
catch { } return firstWeekDay;
} /// <summary>
/// 获取指定日期所在周的第一天,星期一为第一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime GetDateTimeWeekFirstDayMon(DateTime dateTime)
{
DateTime firstWeekDay = DateTime.Now; try
{
int weeknow = Convert.ToInt32(dateTime.DayOfWeek); //星期一为第一天,weeknow等于0时,要向前推6天。
weeknow = (weeknow == ? ( - ) : (weeknow - )); int daydiff = (-) * weeknow; firstWeekDay = dateTime.AddDays(daydiff);
}
catch { } return firstWeekDay;
} /// <summary>
/// 获取指定日期所在周的最后一天,星期六为最后一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime GetDateTimeWeekLastDaySat(DateTime dateTime)
{
DateTime lastWeekDay = DateTime.Now; try
{
int weeknow = Convert.ToInt32(dateTime.DayOfWeek); int daydiff = ( - weeknow) - ; lastWeekDay = dateTime.AddDays(daydiff); }catch { } return lastWeekDay;
} /// <summary>
/// 获取指定日期所在周的最后一天,星期天为最后一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns> public static DateTime GetDateTimeWeekLastDaySun(DateTime dateTime)
{
DateTime lastWeekDay = DateTime.Now; try
{
int weeknow = Convert.ToInt32(dateTime.DayOfWeek); weeknow = (weeknow == ? : weeknow); int daydiff = ( - weeknow); lastWeekDay = dateTime.AddDays(daydiff);
}
catch { } return lastWeekDay;
} /// <summary>
/// 获取指定日期的月份第一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime GetDateTimeMonthFirstDay(DateTime dateTime)
{
if (dateTime == null)
{
dateTime = DateTime.Now;
} return new DateTime(dateTime.Year, dateTime.Month, );
} /// <summary>
/// 获取指定月份最后一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime GetDateTimeMonthLastDay(DateTime dateTime)
{
int day = DateTime.DaysInMonth(dateTime.Year, dateTime.Month); return new DateTime(dateTime.Year, dateTime.Month, day);
}
}
上一篇:pip --upgrade批量更新过期的python库


下一篇:Python基础一(格式化输出、流程控制)