我可以用什么数学公式来计算给定日期的哪一天(例如星期五)
本文关键字:一天 星期五 日期 数学公式 什么 计算 我可以 | 更新日期: 2023-09-27 18:21:33
在不使用DateTimePicker
或其他日历类型的工具或内置功能的情况下,如何从给定日期开始计算日期(例如星期五)?
我想通过提供日期来实现get_Day(desired_Date)
函数。
该函数提供了一个"dd-mmm-yyyy"格式的日期,例如,它被要求返回一个日期字符串。我提供了2014年9月11日,然后函数应该以字符串的形式返回星期四。
有人能帮我做一个数学公式吗?
Microsoft在其DateTime.DayOfWeek C#属性中使用的公式为:
(Ticks / 864000000000L + 1L) % 7L
用法示例:
DateTime samp = new DateTime(2013, 05, 18);
Console.WriteLine(string.Format("Ticks: {0}", samp.Ticks));
Console.WriteLine(string.Format("The day of the week as a number: {0}", (samp.Ticks / 864000000000L + 1L) % 7L)); // The formula they use to calculate day of week
Console.WriteLine(samp.DayOfWeek);
Console.ReadLine();
记号的定义:http://msdn.microsoft.com/en-us/library/system.datetime.ticks%28v=vs.110%29.aspx
这里有一种方法。
#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, difftime, time, mktime */
int main ()
{
time_t timer;
// get time now
timer = time(NULL);
// Our number is the difference between now and 1st Jan 1970 00:00 - our reference time
printf ("%u seconds have passed since since January 1, 1970'n", timer);
// print number of days since reference time
time_t days = timer / (60 * 60 * 24);
printf ("%u days have passed since since January 1, 1970'n", days);
// January 1, 1970 is a Thursday - so we have to cater for that. Easiest is to say Thursday is our reference zero.
// modulo arithmetic to get unadjusted day of week
int ref_thurs_day = days % 7;
printf ("day of week reference to thursday is: %u'n", ref_thurs_day);
switch(ref_thurs_day) {
case 0: puts("Thursday"); break;
case 1: puts("Friday"); break;
case 2: puts("Saturday"); break;
case 3: puts("Sunday"); break;
case 4: puts("Monday"); break;
case 5: puts("Tuesday"); break;
case 6: puts("Wednesday"); break;
default: puts("Something went wrong!");
}
return 0;
}