实施例的代码从用于卵石手表应用程序。代码工作和两个时间戳之间的输出定时,但如何让它更漂亮?
char d[5];
char h[5];
char m[5];
char s[5];
const char *start = "START";
time_t now_time = time(NULL);
int tt = other_time - now_time;
if (tt > 0) {
int rest = tt % 31556926;
int dd = rest / 86400;
rest = tt % 86400;
int hh = rest / 3600;
rest = tt % 3600;
int mm = rest / 60;
int ss = rest % 60;
if (dd > 0)
snprintf(d, sizeof(d), "%dD", dd);
else
snprintf(d, sizeof(d), "%s", "\n");
...
if (ss > 0)
snprintf(s, sizeof(s), " %dS", ss);
else
snprintf(s, sizeof(s), "%s", "\n");
snprintf(string, sizeof(string), "%s%s%s%s", d, h, m, s);
} else {
snprintf(string, sizeof(string), "%s", start);
}
如果“美丽”你的意思是“优雅”(通常被视为“简洁,高效”),我会尝试这样的:
#include <stdio.h>
#include <time.h>
char * getDuration(time_t future)
{
char * duration = (char *) malloc(sizeof(char) * 32);
int elapsed = (int) (future - time(NULL));
if(elapsed > 0)
{
int d = (elapsed % 31556926) / 86400;
int h = (elapsed % 86400) / 3600;
int m = (elapsed % 3600) / 60;
int s = (elapsed % 60) ;
sprintf(duration, "%sD%sH%sM%sS", d, h, m, s);
}
else sprintf(duration, "START");
return duration;
}
PS:我不知道为什么你的字符串,而不是“0D”打印“\ n”,“0H”等。