Last active
June 24, 2025 09:02
-
-
Save xeecos/86f86a4dd19f7b00d27278d60014d7b1 to your computer and use it in GitHub Desktop.
linux. set system time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <time.h> | |
| #include <sys/time.h> | |
| void setSystemTime(int year, int month, int day, int hour, int minute, int second) | |
| { | |
| struct tm *p = new struct tm(); | |
| p->tm_year = year - 1900; | |
| p->tm_mon = month - 1; | |
| p->tm_mday = day; | |
| p->tm_hour = hour; | |
| p->tm_min = minute; | |
| p->tm_sec = second; | |
| time_t utc_t = mktime(p); | |
| delete(p); | |
| struct timeval tv; | |
| struct timezone tz; | |
| gettimeofday(&tv, &tz); | |
| tv.tv_sec = utc_t; | |
| tv.tv_usec = 0; | |
| settimeofday(&tv, &tz); | |
| gettimeofday(&tv, &tz); | |
| } | |
| void get_time(time_t from, int* year, int* month, int* day, int* hour, int* minute, int*second) | |
| { | |
| struct tm *timeinfo = localtime(&from); | |
| *year = timeinfo->tm_year + 1900; | |
| *month = timeinfo->tm_mon + 1; | |
| *day = timeinfo->tm_mday; | |
| *hour = timeinfo->tm_hour; | |
| *minute = timeinfo->tm_min; | |
| *second = timeinfo->tm_sec; | |
| } | |
| svr.Get("/time",[](const Request &req, Response &res){ | |
| struct timeval tv; | |
| struct timezone tz; | |
| gettimeofday(&tv, &tz); | |
| if(req.has_param("time")) | |
| { | |
| time_t t = atoi(req.get_param_value("time").c_str()); | |
| tv.tv_sec = t; | |
| tv.tv_usec = 0; | |
| settimeofday(&tv, &tz); | |
| gettimeofday(&tv, &tz); | |
| return res.set_content("{\"res\":\"done\"}", "application/json"); | |
| } | |
| json info; | |
| info["res"] = "done"; | |
| info["time"] = tv.tv_sec; | |
| int year, month, day, hour, minute, second; | |
| get_time(tv.tv_sec, &year, &month, &day, &hour, &minute, &second); | |
| char date[100]; | |
| sprintf(date, "%d-%d-%d %d:%d:%d", year, month, day, hour, minute, second); | |
| info["info"] = date; | |
| return res.set_content(info.dump(), "application/json"); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment