c - 如何在C编程中制作小时、分钟偏移标志

标签 c unix datetimeoffset

我在 Unix 上使用 C。该程序显示时间,我试图弄清楚如何以分钟和小时为单位偏移当前时间。

这部分代码

  while ( ( let = getopt(argc, argv, "alo:vh")) != -1 ) {
    switch (let) {
    case 'o':  offset = atoi(optarg);  break; }

以及本部分后面的内容:

void clock(int sig, int time_expires)
{
time_t       now;
struct tm   *dateinfo; 

(void) time(&now);
now = now + offset;

dateinfo = localtime( &now ); }

创建一个 -o 偏移量,将当前时间偏移一定的秒数。例如,-o590 会将当前时间偏移 590 秒。

我试图弄清楚如何仅使用一个 -h 标志来完成同样的事情,该标志将时间偏移一定的小时数(例如 -h6 将时间偏移 6 小时)或通过一个 -m 标志来偏移时间以分钟为单位。

我尝试将当前 -o 标志除以 60 或 360,但这不起作用。有人能在这里指出正确的方向吗?

最佳答案

可移植方式将time_t更改这么多小时、分钟、秒,无需依赖time_t是自 1970 年以来的某种整数类型的秒,使用 mktime()

time_t adjust(time_t t, int hour, int minute, int second) {
  struct tm *dateinfo; 
  dateinfo = localtime(&t);
  if (dateinfo == NULL) return (time_t) -1;
  dateinfo->tm_hour += hour;
  dateinfo->tm_min += minute;
  dateinfo->tm_sec += second;
  return mktime(dateinfo);
}

关于c - 如何在C编程中制作小时、分钟偏移标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33512642/

相关文章:

c - FreeBSD 上的 getdate

c - 如果包含数字,如何使整个字符串大写?

c - UDP 接收超时选项 linux c

linux - 如何根据搜索在文件内容中附加字符串

arrays - 从多个数组中提取信息

bash - 使用 head 和 tail 命令显示选定的行

不能使用 fgets() 读取 "consuming it up"之后的文件?

c# - 夏令时更改后的 DateTimeOffset 显示

c# - .Net 中有 ZonedDateTime (Java) 吗?

c# - DateTimeOffset 解析和自定义时区