subtracting days from localtime problem
ALeine
aleine at austrosearch.net
Fri Apr 1 01:15:47 PST 2005
I attached an example which shows the DST related changes
this year. I just couldn't resist writing something where
I get to use rare values such as 1112345678 and 1131131131
in a meaningful way. :-)
ALeine
___________________________________________________________________
WebMail FREE http://mail.austrosearch.net
-------------- next part --------------
/*-
* Copyright (c) 2005 ALeine <aleine at austrosearch.net>
* All rights reserved.
*
* Imported into CVS repository at exactly 1112345678 seconds
* since the Epoch.
*
* $Id: dst_2005.c,v 1.1.1.1 2005/04/01 08:54:38 aleine Exp $
*
*/
#include <stdio.h>
#include <time.h>
void get_date_string_x_days_from_time(char *, size_t, int, time_t);
void get_date_string_x_days_before_time(char *, size_t, int, time_t);
int
main(void)
{
time_t now;
int last_day;
int day_offset;
char date_string[32];
now = time(NULL);
/* Uncomment the following line to see what happens on 01-Apr-2005 */
/* now = 1112345678; */
/* Uncomment the following line to see what happens on 04-Nov-2005 */
/* now = 1131131131; */
fprintf(stderr, "Reference date and time: %s\n", ctime(&now));
last_day = 32;
for (day_offset = 1; day_offset < last_day; day_offset++) {
get_date_string_x_days_before_time(date_string,
sizeof(date_string),
day_offset,
now);
printf("%3d day%c before reference date: %s\n",
day_offset,
(day_offset > 1 ? 's' : ' '),
date_string);
}
return 0;
}
void
get_date_string_x_days_before_time(char *date_string,
size_t size,
int day_offset,
time_t time)
{
get_date_string_x_days_from_time(date_string, size, -day_offset, time);
}
void
get_date_string_x_days_from_time(char *date_string,
size_t size,
int day_offset,
time_t time)
{
struct tm *tm_p;
tm_p = localtime(&time);
tm_p->tm_mday += day_offset;
tm_p->tm_hour = tm_p->tm_min = tm_p->tm_sec = 0;
/* make mktime(3) figure out whether DST is in effect */
tm_p->tm_isdst = -1;
time = mktime(tm_p);
if (time == ((time_t) - 1))
printf("mktime(3) failed\n");
snprintf(date_string, size, "%d-%.2d-%.2d [DST: %d]",
tm_p->tm_year + 1900,
tm_p->tm_mon + 1,
tm_p->tm_mday,
tm_p->tm_isdst);
}
More information about the freebsd-hackers
mailing list