【问题标题】:Date formatting in pure C using time zones使用时区在纯 C 中格式化日期
【发布时间】:2016-05-02 07:05:29
【问题描述】:

我想将 Unix 毫秒转换器实现为人类可读的日期格式。 使用这篇文章https://stackoverflow.com/a/1657307/1979882 我发现我可以收到这样的字符串,但我无法在代码中设置时区。该代码仅使用系统时区。

#include <stdio.h>
#include <time.h>

int main ( int argc, char *argv[] )
{
    time_t now;
    struct tm *lcltime;

    now = time ( NULL );
    lcltime = localtime ( &now );

    printf ( "The time is %d:%d\n", lcltime->tm_hour, lcltime->tm_min );

    return 0;
}

可以自定义吗?

编辑

我需要一些类似 Java 的方法:

SimpleDateFormat df= new SimpleDateFormat("dd MMM hh:mm z",Locale.ENGLISH);
df.setTimeZone("Europe/London");
System.out.println("London Time " + df.format(System.currentTime()));
df.setTimeZone("Asia/Benjin");
System.out.println("Benjin Time " + df.format(System.currentTime()));

EDIT_2

我发现我可以使用 setenv(...) 设置时区 网址 https://stackoverflow.com/a/1620451/1979882

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main (int argc, char *argv[])
{
    struct tm *mt;
    time_t mtt;
    char ftime[10];

    setenv("TZ", "PST8PDT", 1);
    tzset();
    mtt = time(NULL);
    mt = localtime(&mtt);
    strftime(ftime,sizeof(ftime),"%Z %H%M",mt);

    printf("%s\n", ftime);
}

但在更改系统时区。我只需要在我的代码中修改时区。

【问题讨论】:

  • 您能更具体地说明您想要做什么吗? localtime 返回一个以本地时区为系统的时间。
  • 我有点惊讶strftime 不适合您正在尝试做的事情,因为它可以用于格式化时间和日期,看起来就像任何一个可以合乎逻辑的东西(并且不合逻辑地)怀孕。
  • 在您参考的页面上查看程序以打印当前格式化的格林威治标准时间。它应该解释为已经为您的系统定义的本地时间设置不同的环境。回想一下,localtime 调用了tzset 并将根据您当前的系统配置计算时间值。如果要检查与 UTC 的偏移量,请改为调用 gmtime
  • 我已更新我的帖子以清除我的问题。

标签: c unix-timestamp date-formatting


【解决方案1】:

您可以根据所需的时区差异将参数更改为localtime

now += (time_t)(3600*TIME_DIFF_IN_HRS)
lcltime = localtime ( &now );

为了完全便携,您可以通过引用this post获取当前时区

【讨论】:

  • 是否可以知道特定时区的TIME_DIFF_IN_HRS?还是我必须预先定义?
  • 这取决于您要显示的时区和您所在的时区。例如如果您在印度并且想要显示 GMT,则为 -5.5。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多