(c/c++) dd/mm/yyyy hh:ii:ss 到 unix 时间戳

(c/c++) dd/mm/yyyy hh:ii:ss to unix timestamp

给定一个日期字符串dd/mm/yyyy hh:ii:ss,我们希望通过函数将其转换为unix时间戳(10位数字)。

long foo(int yyyy, int mm = 0, int dd = 0, int hh = 0, int ii = 0, int ss = 0) { }

我无法找出给出准确结果的确切公式,匹配 unixtimestamp.com

Unix time is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds.

您可以创建一个 tm 结构(来自 < time.h>/< ctime>)并将这些参数传递给它,然后您可以简单地调用 mktime() 函数或 timegm() 函数,这取决于您要将输入作为本地时间还是 GMT 时间。

有一件事你应该仔细记住,tm结构中实际存储的年份是(year-1990),月份应该是(month-1)。不要忘记设置 tm 的 tm_isdst 标志。可以设置为-1,可以自动检测是否应用夏令时。

例如,您要转换 GMT 11/02/1990 00:16:50。

tm* t;
t->tm_sec = 50;
t->tm_min = 16;
t->tm_hour = 0;
t->tm_mday = 11;
t->tm_mon = 1; // 2-1, not 2!
t->tm_year = 90; // 1990-1900, not 1990!
t->tm_isdst = -1;

然后你可以调用 timegm(t),它会给你结果 634695410。

如评论中所述,strptime 可以为您进行解析以创建 struct tm。然后你可以调用 mktime 得到一个 time_t:

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


int main(void)
{
    struct tm mytm;
    time_t t;
    strptime("31/10/2015 08:33:00","%d/%m/%Y %H:%M:%S",&mytm);
    t = mktime(&mytm);
    printf("t=%ld\n",t);
    return 0;
}

结果:

t=1446294780

在 arduino 上使用时间库 github.com/PaulStoffregen/Time

#include <Time.h>

struct unix {
  long get(int y, int m = 0, int d = 0, int h = 0, int i = 0, int s = 0) {
    setTime(h, i, s, d, m, y);
    adjustTime(-10800); // +3
    return now();
  }
} unix;

void setup() {
  Serial.begin(19200);
  Serial.setTimeout(0);

  Serial.println("..");
  //Serial.println(unix.get(2015));
  //Serial.println(unix.get(2015, 10));
  //Serial.println(unix.get(2015, 10, 31));
  //Serial.println(unix.get(2015, 10, 31, 18));
  //Serial.println(unix.get(2015, 10, 31, 18, 41));
  //Serial.println(unix.get(2015, 10, 31, 18, 41, 0));

  Serial.println("Enter the date (dd/mm/yyyy hh:ii:ss am/pm). Example: \"31/10/2015 7:27 pm\".");
}

void loop() {
  while (Serial.available() > 0) {
    int dd = Serial.readStringUntil('/').toInt();
    int mm = Serial.readStringUntil('/').toInt();
    int yyyy = Serial.readStringUntil(' ').toInt();
    int hh = Serial.readStringUntil(':').toInt();
    int ii = Serial.readStringUntil(':').toInt();
    int ss = Serial.readStringUntil(' ').toInt();
    String pm = Serial.readStringUntil('\n');

    if (pm == 0) pm = "am";
    Serial.print(dd); Serial.print("/");
    Serial.print(mm); Serial.print("/");
    Serial.print(yyyy); Serial.print(" ");
    Serial.print(hh); Serial.print(":");
    Serial.print(ii); Serial.print(":");
    Serial.print(ss); Serial.print(" ");
    Serial.print(pm); Serial.print(" = ");

    if (pm == "pm") hh += 12;
    Serial.println(unix.get(yyyy, mm, dd, hh, ii, ss));
    Serial.println();

    Serial.println("Enter the date (dd/mm/yyyy hh:ii:ss am/pm).");
  }

  delay(50);
}