close

Setup system date/time by timezone in C

 

prerequisiteint matchStrPosAt()char *strmhead()char *strcutail() 

  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
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*
 * tzconfig.c
 *
 * Created by Jackie Xie on 2011-07-17.
 * Copyright 2011 Jackie Xie. All rights reserved.
 *
 */

#include <errno.h>
#include <getopt.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include <sys/time.h>

/* ======================(function header)========================
Function Name:char* itos (){}
Description:to convert integer to string
Arguments:unsigned n
Return:a string
written by jackiexie
Date: 2007/07/10
================================================================*/
char tmpbuf[17];
char* itos (int n)
{
  int i=0,j;
  //char* s;
  //char* u;
  char s[17];
  //s= (char*) malloc(17);
  //u= (char*) malloc(17);
  
  do{
    s[i++]=(char)( n%10+48 );
    n-=n%10;
  }
  while((n/=10)>0);
  for (j=0;j<i;j++)
  tmpbuf[i-1-j]=s[j];

  tmpbuf[j]='\0';
  return tmpbuf;
}

/* ======================(function header)========================
Function Name:int getTZ(char **tz){}
Description : To find the time difference[Coordinated Universal Time
 (UTC)] between GMT and Local time zone.
Arguments : char ** tz
Return : a string with format "[+|-]hh:mm"
written by jackiexie
Date : 2011/06/02
Example :
 int main(int argc, char** argv)
 {
 char *tz;

 getTZ(&tz);
 printf("UTC%s", tz);

 return 0;
 }
================================================================*/
int getTZ(char **tz)
{
	struct tm *tptr;
	char UTC[20];
	time_t secs,l_secs,gmt_secs;
	float utc;
	char *min, *sign;
	int tmp;
	
	time(&secs);
	tptr = localtime(&secs);
	l_secs = mktime(tptr);
	tptr = gmtime(&secs);
	gmt_secs = mktime(tptr);
	utc = l_secs - gmt_secs;
	
	utc = utc/3600.0;
	//utc = -9.9;//-2.5;-3.5;-4.5;-9.5;-12;-10;5.75;8.75;12.75;13.75;14

	if(utc < 0)
		sign = strdup("-");
	else if(utc > 0)
		sign = strdup("+");

	tmp = utc * 60;
	tmp = abs(tmp) % 60;
	
	if(tmp == 30)
		min = strdup("30");
	else if(tmp == 45)
		min = strdup("45");
	else if(tmp != 0)
		min = strdup(itos(tmp));
	else
		min = strdup("00");

	tmp = (int)abs(utc);
	if(tmp <= 14 && tmp >= 10)
		sprintf(UTC, "%s%d:%s", sign, tmp, min);
	else if(tmp < 10 && tmp > 0)
		sprintf(UTC, "%s0%d:%s", sign, tmp, min);
	else
		sprintf(UTC, "00:00");

	*tz = strdup(UTC);
	//printf("%s(%s)\n", UTC, *tz);
	if(*tz == NULL)
		return -1;
	
	free(min);
	free(sign);
	
	return 0;
}

/* ======================(function header)========================
Function Name:int SetTZ(char **tz){}
Description : To Setup the system date、time by timezone information.
Arguments : char * tz
Return : a string with format "[+|-]hh:mm"
written by Jackie Xie
Date : 2011/08/18
================================================================*/
int SetTZ(char *timezone)
{
	struct tm *tptr, time_to_set;
	struct timeval tv;
	struct timezone tz;
	time_t secs;
	int utc = 0;
	int hsecs, msecs;
	int rc;
	char *sHour = strdup(timezone);
	char *sMin = strdup(timezone);

	(void) time(&secs);
	tptr = localtime(&secs);
	printf("時區是:UTC%s\n", timezone);
	printf("目前的日期時間為:\n");
	printf(" 日期: %02d年%02d月%02d日\n", 1900+tptr->tm_year, tptr->tm_mon+1, tptr->tm_mday);
	printf(" 時間: %02d:%02d:%02d\n\n", tptr->tm_hour, tptr->tm_min, tptr->tm_sec);

	if(strstr(timezone,":")){
		hsecs = atoi(strcutail(sHour, ":", -100)) * 3600;
		msecs = atoi(strmhead(sMin, ":", -100)) * 60;
	}
	else{	      
                hsecs = atoi(sHour) * 3600;
                msecs = 0;
        }
         
        utc = hsecs + msecs;
	(void) time(&secs);
	
	if(utc==0)
		tptr = localtime(&secs);
	else{
		secs += utc;
		tptr = gmtime(&secs);
	}

	// Make new system time.
	if ((tv.tv_sec = mktime(tptr)) == (time_t)-1)
	{
		printf("Cannot convert system time\n");
	}

	tz.tz_minuteswest = -(secs / 60);	
	tv.tv_usec = 0;
	rc = settimeofday(&tv, &tz);
	if ( rc != 0)
	{
		printf("Cannot set system time\n");
		printf("settimeofday() failed, " "errno = %d\n",errno);
		return -1;
	}
	else
		printf("settimeofday() successful.\n");


	printf("時區是:UTC%s\n", timezone);
	printf("更新後的日期和時間分別為:\n");
	printf(" 日期: %02d年%02d月%02d日\n", 1900+tptr->tm_year, tptr->tm_mon+1, tptr->tm_mday);
	printf(" 時間: %02d:%02d:%02d\n\n", tptr->tm_hour, tptr->tm_min, tptr->tm_sec);

	free(sMin);
	free(sHour);
	
	return 0;
}

int main(int argc, char *argv[])
{
	struct timeval tv;
	char help_msg[1024] = "Usage: tzconfig [-s <timezone>] [-i] [-h]\n\n";
	char *tz;
	int c;
	
	strcat(help_msg, "tzconfig command summary\n");
	strcat(help_msg, "\ttzconfig is a function to setup/get timezone infomation.\n");
	strcat(help_msg, "\t-s:setup datetime for specified timezone.\n");
	strcat(help_msg, "\t\t<timezone>:input format:'<+ | ->xx:xx' (x=[0~9]).\n");
	strcat(help_msg, "\t-i:To get te local timezone information.\n");
	strcat(help_msg, "\t-h:To show this help message.\n");

	while ((c = getopt(argc, argv, "s:i0:h0:?0")) != -1)
		switch (c) {
			case 's':
				tz = optarg;
				SetTZ(tz);
				break;
			case 'i':
				getTZ(&tz);
				printf("本地時區是:UTC%s\n", tz);
				break;
			case 'h':
			case '?':
				fprintf(stderr, "%s", help_msg);
				exit(0);
				break;
			default:
				break;
		}

	return 0;
}

To run this program...

[ jackie macbook-pro-3 ~ ]# ./tzconfig -h
Usage: tzconfig [-s <timezone>] [-i] [-h]

tzconfig command summary
        tzconfig is a function to setup/get timezone infomation.
        -s:setup datetime for specified timezone.
                <timezone>:input format:'<+ | ->xx:xx' (x=[0~9]).
        -i:To get te local timezone information.
        -h:To show this help message.
[ jackie macbook-pro-3 ~ ]# ./tzconfig -?
Usage: tzconfig [-s <timezone>] [-i] [-h]

tzconfig command summary
        tzconfig is a function to setup/get timezone infomation.
        -s:setup datetime for specified timezone.
                <timezone>:input format:'<+ | ->xx:xx' (x=[0~9]).
        -i:To get te local timezone information.
        -h:To show this help message.
[ jackie macbook-pro-3 ~ ]# sudo ./tzconfig -i
Password:
本地時區是:UTC+08:00
[ jackie macbook-pro-3 ~ ]# ./tzconfig -i
本地時區是:UTC+08:00
[ jackie macbook-pro-3 ~ ]# ./tzconfig -s +14:00
時區是:UTC+14:00
目前的日期時間為:
        日期: 2011年08月19日
        時間: 17:19:04

Cannot set system time
settimeofday() failed, errno = 1
[ jackie macbook-pro-3 ~ ]# sudo ./tzconfig -s +14:00
時區是:UTC+14:00
目前的日期時間為:
        日期: 2011年08月19日
        時間: 17:19:10

settimeofday() successful.
時區是:UTC+14:00
更新後的日期和時間分別為:
        日期: 2011年08月19日
        時間: 23:19:10

[ jackie macbook-pro-3 ~ ]# ./tzconfig -i
本地時區是:UTC+08:00
[ jackie macbook-pro-3 ~ ]# sudo ./tzconfig -s +08:00
Password:
時區是:UTC+08:00
目前的日期時間為:
        日期: 2011年08月19日
        時間: 23:19:45

settimeofday() successful.
時區是:UTC+08:00
更新後的日期和時間分別為:
        日期: 2011年08月19日
        時間: 23:19:45

[ jackie macbook-pro-3 ~ ]# sudo ./tzconfig -s -08:00
時區是:UTC-08:00
目前的日期時間為:
        日期: 2011年08月19日
        時間: 23:20:07

settimeofday() successful.
時區是:UTC-08:00
更新後的日期和時間分別為:
        日期: 2011年08月19日
        時間: 07:20:07

[ jackie macbook-pro-3 ~ ]# sudo ./tzconfig -s +18:00
sudo: timestamp too far in the future: Aug 19 23:20:06 2011

WARNING: Improper use of the sudo command could lead to data loss
or the deletion of important system files. Please double-check your
typing when using sudo. Type "man sudo" for more information.

To proceed, enter your password, or type Ctrl-C to abort.

Password:
時區是:UTC+18:00
目前的日期時間為:
        日期: 2011年08月19日
        時間: 07:20:40

settimeofday() successful.
時區是:UTC+18:00
更新後的日期和時間分別為:
        日期: 2011年08月19日
        時間: 17:20:40

[ jackie macbook-pro-3 ~ ]#

 

Date and Time

ISO 8601

UNIX時間

Coordinated Universal Time

Time Zone and other travel tools

Sources for Time Zone and Daylight Saving Time Data

settimeofday

settimeofday()--Set System Clock

Setting the timezone on OpenWrt

OpenWRT and Time zone

Time Zones on OpenWrt

Time Synchronisation on OpenWrt

netcwmp

Setup system datetime by local time zone name which is encoded according to IEEE 1003.1 (POSIX) in C

arrow
arrow
    文章標籤
    Time Time zone
    全站熱搜

    Bluelove1968 發表在 痞客邦 留言(0) 人氣()