加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 获取给定周年,给定月份和给定周的开始和结束日期

发布时间:2020-12-15 04:36:01 所属栏目:百科 来源:网络整理
导读:如何在c#4.0中获取给定年份(int),给定月份(int)和给定周(int){示例年份:2011月份:07周:04}的开始和结束日期?提前致谢. 2011年07月的开始日期和月份的周数是04. 解决方法 Google是你的朋友. 月: public DateTime FirstDayOfMonthFromDateTime(DateTime d
如何在c#4.0中获取给定年份(int),给定月份(int)和给定周(int){示例年份:2011月份:07周:04}的开始和结束日期?提前致谢.

2011年07月的开始日期和月份的周数是04.

解决方法

Google是你的朋友.

月:

public DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
   return new DateTime(dateTime.Year,dateTime.Month,1);
}


public DateTime LastDayOfMonthFromDateTime(DateTime dateTime)
{
   DateTime firstDayOfTheMonth = new DateTime(dateTime.Year,1);
   return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
}

您可以多年来做类似的事情:

DateTime time = new DateTime(2011,1,1);
   time.AddYears(1).AddDays(-1);

week需要使用CultureInfo.FirstDay(或者你想要设置为一周的第一天,在某些国家是星期一,有时是星期天).

/// <summary>
    /// Returns the first day of the week that the specified
    /// date is in using the current culture. 
    /// </summary>
    public static DateTime GetFirstDayOfWeek(DateTime dayInWeek)
    {
        CultureInfo defaultCultureInfo = CultureInfo.CurrentCulture;
        return GetFirstDateOfWeek(dayInWeek,defaultCultureInfo);
    }

    /// <summary>
    /// Returns the first day of the week that the specified date 
    /// is in. 
    /// </summary>
    public static DateTime GetFirstDayOfWeek(DateTime dayInWeek,CultureInfo cultureInfo)
    {
        DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;
        DateTime firstDayInWeek = dayInWeek.Date;
        while (firstDayInWeek.DayOfWeek != firstDay)
            firstDayInWeek = firstDayInWeek.AddDays(-1);

        return firstDayInWeek;
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读