C#显示DateTime的星期的方法

时间:2021-04-16

  DateTime 的 ToString 并没有格式化星期这一东西。

  网上说这么用:

  System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek)

  上面显示计算机当前设置的星期,受控制面板中“区域和语言选项”的影响。若要显示特定区域和语言的星期,可使用下面的代码:

  System.Globalization.CultureInfo.GetCultureInfo("zh-CN").DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek)

  当然,如果觉得不放心,还有另外一种方法,也就是自己写方法:

protected void Page_Load(object sender, EventArgs e)
{
_result.Text = "今天是:" + DateTime.Now.ToString("yyyy年MM月dd日") + " " + GetDayName();
}

private string GetDayName()
{
string result = "";

DateTime today = DateTime.Now;
if (today.DayOfWeek == DayOfWeek.Monday)
{
result = "星期一";
}
else if (today.DayOfWeek == DayOfWeek.Tuesday)
{
result = "星期二";
}
else if (today.DayOfWeek == DayOfWeek.Wednesday)
{
result = "星期三";
}
else if (today.DayOfWeek == DayOfWeek.Thursday)
{
result = "星期四";
}
else if (today.DayOfWeek == DayOfWeek.Friday)
{
result = "星期五";
}
else if (today.DayOfWeek == DayOfWeek.Saturday)
{
result = "星期六";
}
else if (today.DayOfWeek == DayOfWeek.Sunday)
{
result = "星期日";
}

return result;
}

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

相关文章