close

Date format converter

  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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/*
 * dtconfig.c
 *
 * Created by Jackie Xie on 2012-02-09.
 * Copyright 2011 Jackie Xie. All rights reserved.
 *
 */

#include <ctype.h>
#include <errno.h>
#include <getopt.h>
#include <math.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 *GetStrBetweenStr(char *,
 char *,char *)
Description: retrieve a string from between left position
 and right position string.
Arguments:char *s,char *lstr,char *rstr
Return: string
written by jackie xie
Date: 2007/07/10
================================================================*/
char *GetStrBetweenStr(char *s,char *lstr,char *rstr)
{
   char *p=s,*lp=s,*rp;
   do
   {
      /*trim(lstr);
 trim(rstr);*/
      lp=strstr(lp,lstr);
      if(lp)
      {
         rp=lstr;
         do lp++; while(*rp++);
         lp--;
         rp=strstr(lp,rstr);
         if(rp)
         {
            if(lp!=rp)
            {
               do *p++=*lp++; while(lp<rp);
               lp--;
            }
            rp=rstr;
            do lp++; while(*rp++);
            lp--;
         }
      }
   } while(lp);
   *p=0;
   return s;
}

/* ======================(function header)========================
Function Name: int matchStrPosAt (const char *, const char *)
Description: find the sub-string from the source string.
Arguments: const char *, const char *
Return: Returns "the array element number"(or "position") where 
 "sub-string" matches before in "original string", or return 
 "-1" if substr is not present in "original string".
written by jackie xie
Date : 2007/07/10
================================================================*/
/* 
 * delimiters <= n:return position before n-th matched substr.
 * delimiters = 0:do nothing.
 * delimiters >= n:return position after n-th matched substr.
 */
int matchStrPosAt (char * substr, char * str, int delimiters)
{
	int i = -1, k, str_index, total = 0;
	int substr_len = strlen(substr), str_len = strlen(str);
	int matchpos = -1;
	int delimiter[str_len], ind_delim = 0;
	//int n = abs(delimiters);

	for(k=0; k<=str_len ; k++)
		delimiter[k] = -1;

	if (str == NULL || substr == NULL) return -1;

	/* substr has to be smaller than str */
	if (substr_len > str_len) return -1;

	/* look through str for substr, stopping at end of string or when the length
 * of substr exceeds the remaining number of characters to be searched */ 
	while (str[++i] != '\0' && (str_len - i + 1) > substr_len) 
	{
		for (str_index = 0; str_index < substr_len; ++str_index)
		{
			/* definitely not at location i */
			if (str[i + str_index] != substr[str_index])
				break;
			/* if last letter matches, then we know the whole thing matched */
			else if (str_index == substr_len - 1)
			{
				if(delimiters >= 1)
				{
					i += substr_len -1;
					delimiter[++ind_delim] = i;
					//printf("delimiter[%d] = %d\n", ind_delim, delimiter[ind_delim]);
				}
				else if(delimiters == 0)
					return i;
				else if(delimiters == -1)
					total++;
			}
		}
	}

	if(delimiters == 0)
		return -1;						/* substr not present in str */
	else if(delimiters == -1)
		return total;					/* the total numbers of substr */
	else if(delimiters < ind_delim)
		matchpos = delimiter[delimiters];
	else
		matchpos = delimiter[ind_delim];

	return matchpos;
}

/* ======================(function header)========================
Function Name: int strcutail (char *str, const char *n, int pos)
Description: To remove the sub-string which is starting at 
 n-th delimiter(or include it) to the end of input string.
Arguments: char *, const char *
Return: Returns the string which was cut the tailed sub-string off.
written by Jackie Xie
Date : 2011/07/15
================================================================*/
char *strcutail (char *str, const char *n, int pos)
{
	int i, _newStrLen = matchStrPosAt(n, str, abs(pos));
	char* _new;
	
	if(_newStrLen >= 0){
		if (pos >= 0)
			++_newStrLen;			
		if ((_new = (char *)malloc(_newStrLen)) == NULL)
			return "NULL";

		(_new)[_newStrLen] = '\0';		

		/* copy sub-string from the head of the string to the specified delimiter */
		for (i = 0; i < _newStrLen; ++i)
			(_new)[i] = str[i];

		strcpy(str, _new);
		free (_new);
	}
	return str;
}

/* ======================(function header)========================
Function Name: int strmhead (char *str, const char *n, int pos)
Description: To cut the front of sub-string which is starting at the
 matched delimiter and ending of the input string.
Arguments: char *, const char *
Return: The string which was cut the front of input string till the 
 specified delimiter.
written by Jackie Xie
Date : 2011/08/12
================================================================*/
char *strmhead (char *str, const char *n, int pos)
{
	int i, _matchedStrLen = matchStrPosAt(n, str, abs(pos));
	int str_len = strlen(str);
	int _newStrLen = 0;
	
	char* _new;
	
	if(_matchedStrLen >= 0){
		if (pos >= 0)
			_matchedStrLen -= strlen(n);
			
		_newStrLen = str_len - _matchedStrLen;

		if ((_new = (char *)malloc(_newStrLen)) == NULL)
			return "NULL";

		(_new)[_newStrLen+1] = '\0';		

		/* copy sub-string from specified delimiter */
		for (i = 0; i < _newStrLen; ++i)
			(_new)[i] = str[_matchedStrLen +1 + i];
		strcpy(str, _new);
		free (_new);
	}
	
	return str;
}

bool isLeapYear (int year)
{
	if(((year % 4==0) && (year%100 != 0)) || (year % 400 == 0))
	   return true;
	else
		return false;	
}

/*
 * Convert a date to days since 1970.
 * written by jackiexie
 * Date : 2012/02/08
 */
int date2jds(char* datetime)
{
	time_t when;
	struct tm	tm;
	char	*end;

	memset(&tm, 0, sizeof(tm));
	end = strptime(datetime, "%Y-%m-%d", &tm);
	if (end == NULL || *end) {
		fprintf(stderr, "could not parse: %s\n", datetime);
		return 0;
	}

	when = mktime(&tm) / 86400;
	//printf("%u\n", (unsigned) (when));
	return when;
}

/*
 * Convert days since 1970 to a date.
 * written by jackiexie
 * Date : 2012/02/08
 */
int jds2date(int days, char* datetime)
{
	time_t when;
	struct tm	*whentm;
	char	res[64];

	when = days * 24 * 60 * 60;
	if ((whentm = localtime(&when)) == NULL) {
		fprintf(stderr, "localtime: %s\n", strerror(errno));
		return -1;
	}

	strftime(res, sizeof(res) - 1, "%Y-%m-%d", whentm);
	res[sizeof(res) - 1] = '\0';
	//printf("%s\n", res);
	sprintf(datetime, "%s", res);

	return 0;
}

/*
 * Convert [J]<days> to M<month>,<week of month>,<week day> format.
 * written by jackiexie
 * Date : 2012/02/08
 */
int jds2mds(int days, char* dst)
{
	time_t when;
	struct tm	*whentm;
	char	month[4], DayOfMonth[3], weekday[3];
	int WeekOfMonth;

	when = days * 24 * 60 * 60;
	if ((whentm = localtime(&when)) == NULL) {
		fprintf(stderr, "localtime: %s\n", strerror(errno));
		return -1;
	}

	strftime(month, sizeof(month) - 1, "M%m", whentm);
	month[sizeof(month) - 1] = '\0';

	strftime(DayOfMonth, sizeof(DayOfMonth) - 1, "%d", whentm);
	DayOfMonth[sizeof(DayOfMonth) - 1] = '\0';
	/* To find current 'week of month'(by 'day of month'(DayOfMonth) */
	WeekOfMonth = ceil(atof(DayOfMonth) / 7);

	strftime(weekday, sizeof(weekday) - 1, "%w", whentm);
	weekday[sizeof(weekday) - 1] = '\0';

	//printf("%s.%d.%s\n", month, WeekOfMonth, weekday);
	sprintf(dst, "%s.%d.%s", month, WeekOfMonth, weekday);

	return 0;
}

/*
 * Convert days to a date format.
 * written by jackiexie
 * Date : 2012/02/08
 */
int days2date(int Days, char* dst)
{
	time_t baseTime;
	struct tm* pLocalTime=NULL;
	char dt[20];
	int jdays = 0;

	baseTime = time(NULL);
	pLocalTime = localtime(&baseTime);
	pLocalTime->tm_year += 1900;

	sprintf(dt, "%d-1-1", pLocalTime->tm_year);
	jdays = Days + date2jds(dt);
	jdays = (isLeapYear(pLocalTime->tm_year))? jdays+1:jdays;
	jds2date(jdays, dst);
	//return jds2mds(jdays, dst);
	return jdays;
}

/*
 * Convert date to a days format.
 * written by jackiexie
 * Date : 2012/02/08
 */
 int date2days(char* date)
 {
	time_t when;
	struct tm	tm;
	char	*end, dt[20], *year, *month, *day;
	int days = 0, day_of_month = 0;

	year = strdup(date);
	month = strdup(date);
	day  = strdup(date);
	strcutail(year, "-", -1);
	GetStrBetweenStr(month, "-", "-");
	strmhead(day, "-", -2);
	day_of_month = atoi(day);
	sprintf(dt, "%s-1-1", year);
	days = date2jds(dt);
	memset(&tm, 0, sizeof(tm));
	end = strptime(date, "%Y-%m-%d", &tm);
	if (end == NULL || *end || (!strcmp(month, "2") && 
		((day_of_month >= 29 && !isLeapYear(atoi(year))) || 
			(day_of_month > 29 && isLeapYear(atoi(year)))))) {
		fprintf(stderr, "could not parse: %s\n", date);
		return -1;
	}

	when = mktime(&tm) / 86400 - days + 1;
	if(isLeapYear(atoi(year))) --when;
	//printf("date2days = %u\n", (unsigned) (when));
	free(year);

	return when;
 }

int main(int argc, char *argv[])
{
	char help_msg[1024] = "Usage: dtconfig [-d yyyy-mm-dd] [-j <days of this year>] [-m <[J]<days of this year>] [-h]\n\n";
	char *date, dst[64], *tmp;
	int c, days;

	strcat(help_msg, "dtconfig command summary\n");
	strcat(help_msg, "\tdtconfig is a function to convert date format.\n");
	strcat(help_msg, "\t-d:To convert date to days.\n");
	strcat(help_msg, "\t-j:To convert days to date.\n");
	strcat(help_msg, "\t\t leap year : 0 ~ 365 \n");
	strcat(help_msg, "\t\t otherwise : 1 ~ 365 \n");
	strcat(help_msg, "\t-m:To convert 'Jn' to 'Mm.w.d' format. \n");
	strcat(help_msg, "\t\t where 'Jn' is specifies the Julian day, with n between 1 and 365. February 29 is never counted, even in leap years. \n");
	strcat(help_msg, "\t\t where 'n' is the days of this year which means the Julian day, with n between 0 and 365. February 29 is counted in leap years. \n");
	strcat(help_msg, "\t-h:To show this help message.\n");

	if(argc <= 1 || ((isgraph(*argv[1]) || ispunct(*argv[1])) && *argv[1]!='-'))
		fprintf(stderr, "%s", help_msg);

	while ((c = getopt(argc, argv, "D:d:J:j:M:m:h0:?0:0:-")) != -1){
		switch (c) {
			case 'D':
			case 'd':
				date = optarg;
				days = date2days(date);
				printf("%d\n", days);
				break;
			case 'J':
			case 'j':
				days = atoi(optarg);
				date = strdup("yyyy-mm-dd");
				days2date(days, date);
				printf("%s\n", date);
				free(date);
				break;
			case 'M':
			case 'm':
				tmp = strdup(optarg);
				if(strstr(tmp, "J")){
					days = atoi(strmhead(tmp, "J", -1));
					if(days != 59){
						days = days2date(days, dst);
						jds2mds(days, dst);
					}
					else
						printf("Invalid !!!\n");
				}
				else{
					days = atoi(optarg);
					/* step 1 : to find the date by days */
					days = days2date(days, dst);
					/* step 2 : to find the result by Julian day & date */
					jds2mds(days, dst);
				}
				printf("%s\n", dst);
				free(tmp);
				break;
			case 'h':
			case '?':
			default:
				fprintf(stderr, "%s", help_msg);
				exit(0);
				break;
		}
	}

	return 0;
}

 

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

Datetime examples

arrow
arrow
    全站熱搜

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