c#得到本月有几周和这几周的起止时间示例代码

时间:2021-05-20

示例代码:
复制代码 代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

</script>
</head>
<body>
<form id="form1" runat="server">
<div>

<%

NumWeeks(new DateTime(2009, 11, 15));

%>

<script runat="server" type="text/C#">

/// <summary>
/// 获得本月有几周
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
public void NumWeeks(DateTime dt)
{
//年
int year = dt.Year;
//月
int month = dt.Month;
//当前月第一天
DateTime weekStart = new DateTime(year, month, 1);
//该月的最后一天
DateTime monEnd = weekStart.AddMonths(1).AddDays(-1);
int i = 1;
//当前月第一天是星期几
int dayOfWeek = Convert.ToInt32(weekStart.DayOfWeek.ToString("d"));
//该月第一周结束日期
DateTime weekEnd = dayOfWeek == 0 ? weekStart : weekStart.AddDays(7 - dayOfWeek);

richTextBox2.Text += "第" + i + "周起始日期: " + weekStart.ToShortDateString() + " 结束日期: " + weekEnd.ToShortDateString() + "\n";

//当日期小于或等于该月的最后一天
while (weekEnd.AddDays(1) <= monEnd)
{
i++;
//该周的开始时间
weekStart = weekEnd.AddDays(1);
//该周结束时间
weekEnd = weekEnd.AddDays(7) > monEnd ? monEnd : weekEnd.AddDays(7);

richTextBox2.Text += "第" + i + "周起始日期: " + weekStart.ToShortDateString() + " 结束日期: " + weekEnd.ToShortDateString() + "\n";
}

richTextBox2.Text += year + "年" + month + "月共有" + i + "周\n";
}

</script>

<asp:TextBox ID="richTextBox2" runat="server" TextMode="MultiLine" Height="321px"
Width="845px" ></asp:TextBox>

</div>
</form>
</body>
</html>

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章