1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| #include <stdio.h> #include <string> #include <time.h> using namespace std;
time_t convertDateToTimestamp(const string &date) { char dateTimeBuf[64]; snprintf(dateTimeBuf, sizeof(dateTimeBuf), "%s 00:00:00", date.c_str()); struct tm dateTM; strptime(dateTimeBuf, "%Y-%m-%d %H:%M:%S", &dateTM); return mktime(&dateTM); }
time_t convertDatetimeToTimestamp(const string &date_time) { struct tm dtTM; strptime(date_time.c_str(), "%Y-%m-%d %H:%M:%S", &dtTM); return mktime(&dtTM); }
void convertTimestampToDate(time_t timestamp, string &date) { struct tm dateTm; localtime_r(×tamp, &dateTm); printf("%d-%d-%d\n", dateTm.tm_year + 1900, dateTm.tm_mon + 1, dateTm.tm_mday); char dateBuf[16]; strftime(dateBuf, sizeof(dateBuf), "%Y-%m-%d", &dateTm); date = dateBuf; }
void convertTimestampToDatetime(time_t timestamp, string &date_time) { struct tm dateTimeTm; localtime_r(×tamp, &dateTimeTm); char dateTimeBuf[32]; strftime(dateTimeBuf, sizeof(dateTimeBuf), "%Y-%m-%d %H:%M:%S", &dateTimeTm); date_time = dateTimeBuf; }
int main(int argc, char const *argv[]) { printf("%d\n", convertDateToTimestamp("2022-09-23")); printf("%d\n", convertDatetimeToTimestamp("2022-09-23 15:23:59")); string date; string date_time; convertTimestampToDate(1663917839, date); convertTimestampToDatetime(1663917839, date_time);
printf("%s\n", date.c_str()); printf("%s\n", date_time.c_str()); return 0; }
|