Get WeekDay Using Pure Date in C#

---
date: Apr 16, 2015
tags:
- C#
language: English
---

Recently, I need to get a weekday purely based on date. Luckily, I find a mathematical way to solve this problem. In this example, it will load the weekday in the TextBox1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
protected void Page_Load(object sender, EventArgs e)
{
int m = System.DateTime.Today.Month;
int y = System.DateTime.Today.Year;
int d = System.DateTime.Today.Day;
int weeks = getWeekDay(y, m, d);
switch (weeks)
{
case 1:
this.TextBox1.Text = "Monday";
break;
case 2:
this.TextBox1.Text = "Tuesday";
break;
case 3:
this.TextBox1.Text = "Wednesday";
break;
case 4:
this.TextBox1.Text = "Thursday";
break;
case 5:
this.TextBox1.Text = "Friday";
break;
case 6:
this.TextBox1.Text = "Saturday";
break;
case 7:
this.TextBox1.Text = "Sunday";
break;
}
}



/// <summary>Get WeekDay Using Date</summary>
/// <param name="y">Year</param>
/// <param name="m">Month</param>
/// <param name="d">Day</param>
/// <returns>WeekDay</returns>
public static int getWeekDay(int y, int m, int d)
{
if (m == 1) m = 13;
if (m == 2) m = 14;
int week = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7 + 1;
return week;
}

Navigation


Creative Commons License

Unless specified, all the articles are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.


It uses a self-hosted Open Web Analytics to get insights. Click here to optout.

The site is powered by Hexo. The source code of this website is here, so that you can see the spaghetti code behind my blog.


Main | Blog | Comic | Podcasts (Preparing) | RSS | Sitemap
2008 - 2022 | Patrick WU Jinming