C# 日期處理

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

namespace WyfClass
{
public class tools
{
/// <summary>
/// 獲得本週第一天(以星期天爲第一天)
/// </summary>
/// <param name="datetime"></param>
/// <returns></returns>
public DateTime GetWeekFirstDaySun(DateTime datetime)
{
    //星期天爲第一天
    int weeknow = Convert.ToInt32(datetime.DayOfWeek);
    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 DateTime GetWeekFirstDayMon(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 DateTime GetWeekLastDaySat(DateTime datetime)
{
    //星期六爲最後一天
    int weeknow = Convert.ToInt32(datetime.DayOfWeek);
    int daydiff = (7 - weeknow) - 1;

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

/// <summary>
/// 獲得本週最後一天(以星期天爲最後一天)
/// </summary>
/// <param name="datetime"></param>
/// <returns></returns>
public DateTime GetWeekLastDaySun(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);
}
}
}
相關文章
相關標籤/搜索