我想在Linux C中获取星期六的星期几。使用函数时间和本地时间,我得到了今天的日期和时间详细信息。如何进一步了解星期六的约会?
#include <time.h>
#include <stdio.h>
#include <string.h>
int main()
{
char date[20];
struct tm *curr_tm = NULL;
time_t curr_time;
curr_time = time(NULL);
curr_tm = localtime(&curr_time);
curr_tm->tm_wday = 6;
//Refers to saturday.
printf("new date %d\t%d\t%d\n", curr_tm->tm_mday, curr_tm->tm_mon, curr_tm->tm_year+1900);
return 1;
}
我该如何处理?
答案 0 :(得分:3)
struct tm orig;
// ...
// struct tm correctly set with everything within range.
orig.tm_mday += 6 - orig.tm_wday;
mktime(&orig);
tm_mday
是自星期日以来的天数。因此,6减去这是直到星期六的天数(如果今天是星期六它什么都不做)。这会使结构超出范围,mktime
已修复。
编辑:
curr_time->tm_mday += 6 - curr_time->tm_wday;
mktime(curr_time);
答案 1 :(得分:2)
根据您的代码,以下内容将为您提供下周六(今天是星期六)。
#include <time.h>
#include <stdio.h>
#include <string.h>
int main() {
char date[20];
struct tm *curr_tm = NULL;
time_t curr_time;
curr_time = time(NULL);
curr_tm = localtime(&curr_time);
// Add the difference between todays day of week and Saturday, then re-make.
curr_tm->tm_mday += 6 - curr_tm->tm_wday;
mktime (curr_tm);
printf("new date %d\t%d\t%d\n",
curr_tm->tm_mday, curr_tm->tm_mon+1, curr_tm->tm_year+1900);
return 1;
}
您可以将curr_tm->tm_mday += 6 - curr_tm->tm_wday;
行替换为:
curr_tm->tm_mday += (curr_tm->tm_wday == 6) ? 7 : 6 - curr_tm->tm_wday;
即使今天是星期六,也要到下个星期六。