我可以使用什么数学公式来获取给定日期的某一天(例如星期五)?

时间:2014-09-11 09:34:22

标签: c# c math calendar formula

如何在不使用DateTimePicker或其他日历类型的工具或内置函数的情况下从指定日期获取当天(例如星期五)?

我希望通过提供日期来实现get_Day(desired_Date)功能。

该函数以“dd-mmm-yyyy”格式提供日期,并且例如请求返回当天的字符串。我提供2014年9月11日,然后该函数应该作为字符串返回星期四。

任何人都可以帮我解决数学公式吗?

3 个答案:

答案 0 :(得分:1)

DateTime dateValue = new DateTime(2014, 9, 12);
Console.WriteLine(dateValue.DayOfWeek);     

查看strptime

int get_weekday(char * str) {
  struct tm tm;
  if (strptime(str, "%d-%m-%Y", &tm) != NULL) {
    time_t t = mktime(&tm);
    return localtime(&t)->tm_wday; // Sunday=0, Monday=1......
  }
  return -1;
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

这是一种方法。

#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;
}