C程序找到周定日期的天 [英] C Program to find day of week given date

查看:129
本文介绍了C程序找到周定日期的天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法找出给定日期的星期几,在短短一行C $ C $的C?

Is there a way to find out day of the week given date in just one line of C code?

例如

由于19-05-2011(DD-MM-YYYY)给我周四

Given 19-05-2011(dd-mm-yyyy) gives me Thursday

推荐答案

一个单行的可能性不大,但的 strptime功能可以用来解析您的日期格式和结构TM 参数可以查询其 tm_wday 成员。

A one-liner is unlikely, but the strptime function can be used to parse your date format and the struct tm argument can be queried for its tm_wday member.

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, etc.
  }
  return -1;
}

或者你可以连接code这些规则做一些算术很长的单行:

Or you could encode these rules to do some arithmetic in a really long single line:


  • 1900年1月1日是个周一。

  • 三十天都有九月,四月,六月和十一月;剩下都是31,单独保存二月,其中有28,风雨无阻,和闰年,29。

  • 闰年发生在任何一年能被4整除,但不能在一个世纪,除非它是被400整除。

这篇关于C程序找到周定日期的天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆