需求如下:
Phil
As you know in North America we change time twice a year – 1 hour forward in Spring and 1 hour back in Fall.
This means all terminal users need to go in Date/time settings to change the time manually.
The time change happens 2nd Sunday of March (1 hour forward) at 2 am and 1st Sunday of November at 2 am (1 hour back).
Can this time change be automated in the kernel or app manager or OS level so the user doesn’t have to do this manually?
Shelly
解决方案
第一步:
copy或者ln -s一个属于夏令时的时区文件(如New_York)到/etc/localtime
cp /usr/share/zoneinfo/America/New_York /etc/localtime
第二步:
写一个测试程序测试下
int main(int argc, char** argv)
{
time_t currtime;
char ptchTime[30];
struct tm* pTm;
time(&currtime);
pTm = localtime(&currtime);
if (pTm)
{
sprintf(ptchTime, "%02d%02d%02d %02d%02d%02d[DST=%d]\n",
pTm->tm_year%100, pTm->tm_mon+1, pTm->tm_mday,
pTm->tm_hour, pTm->tm_min, pTm->tm_sec, pTm->tm_isdst);
}
printf(ptchTime);
struct tm tm_new;
time_t the_time;
tm_new.tm_year = 113; tm_new.tm_mon = 10; tm_new.tm_mday = 3;
tm_new.tm_hour = 1; tm_new.tm_min = 59; tm_new.tm_sec = 0;
printf("tm_new est=%d\n", tm_new.tm_isdst);
the_time=mktime(&tm_new);
//update system time
stime((long*)&the_time);
//update hardware time
system("hwclock -w");
time(&currtime);
pTm = localtime(&currtime);
if (pTm)
{
sprintf(ptchTime, "%02d%02d%02d %02d%02d%02d[DST=%d]\n",
pTm->tm_year%100, pTm->tm_mon+1, pTm->tm_mday,
pTm->tm_hour, pTm->tm_min, pTm->tm_sec, pTm->tm_isdst);
}
printf(ptchTime);
return 0;
}
测试发现3月可自动进一个小时,可是11月时间不变。。原来没初始化:
memset((char*)&tm_new, 0 ,sizeof(struct tm));
同时man mktime查看结构体定义如下:
Broken-down time is stored in the structure tm which is defined in <time.h> as follows:
struct tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
int tm_wday; /* day of the week */
int tm_yday; /* day in the year */
int tm_isdst; /* daylight saving time */
};
The members of the tm structure are:
tm_sec The number of seconds after the minute, normally in the range 0 to 59, but can be up to 60 to allow for leap seconds.
tm_min The number of minutes after the hour, in the range 0 to 59.
tm_hour The number of hours past midnight, in the range 0 to 23.
tm_mday The day of the month, in the range 1 to 31.
tm_mon The number of months since January, in th