简体   繁体   English

从UNIX时间戳获取同月第一天的时间戳,而无需进行任何到本地时间的转换

[英]Get timestamp of first day of the same month from UNIX timestamp without any conversions to local time

Suppose that I have UNIX timestamp like this 假设我有这样的UNIX时间戳

1252301772

and I need to convert it to another timestamp representing the first day of the same month (without any conversions to the local time or something like this). 并且我需要将其转换为表示同一个月第一天的另一个时间戳(不转换为本地时间或类似的时间)。 Example: 例:

1252301772 -> 07 Sep 2009 05:36:12 GMT
x -> 01 Sep 2009 00:00:00 GMT
#include <time.h>

time_t first_of_the_month(time_t t)
{
  struct tm tmt;
  if (!gmtime_r(&t, &tmt))
    return -1;
  tmt.tm_sec = 0;
  tmt.tm_min = 0;
  tmt.tm_hour = 0;
  tmt.tm_mday = 1;
  tmt.tm_isdst = -1;
  return timegm(&tmt);
}

This uses the non-standard timegm function (thanks to Jeremy Friesner for pointing that out). 这使用了非标准的timegm函数(感谢Jeremy Friesner指出了这一点)。 If that function isn't available on your platform you can use mktime but that depends on the local timezone, so you would need to adjust the program's timezone (by setting TZ in the environment and calling tzset) before and after calling mktime , which is not thread-safe because it alters global program state. 如果该功能在您的平台上不可用,则可以使用mktime但这取决于本地时区,因此您需要在调用mktime之前和之后调整程序的时区(通过在环境中设置TZ并调用tzset)。不是线程安全的,因为它会更改全局程序状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM