‘localtime()’ loves ’05:30:00′

Hi friends,

Got some problem when I’m converting elapsed time ‘time_t’ to ‘struct tm’ for printing time in ‘%H:%M:%S” format. Here is the code,

/* code to learn how 'localtime()' works */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char **argv)
{
	struct tm time1;
	struct tm *time2;
	time_t time;
	char timestring[20];

	time2 = (struct tm *)malloc(sizeof(struct tm));

	/* setting 0 seconds to time */
	time = (time_t) 0;
	localtime_r(&time, &time1);

	time1.tm_hour = time1.tm_hour - 5;
	time1.tm_min = time1.tm_min - 30;

	strftime(timestring,
		20,
		"%H:%M:%S",
		&time1);
	printf("Time1: %s\n",
		timestring);

	/* setting 1 minute 10 seconds to time */
	time = (time_t) 70;
	time2 = localtime(&time);

	time2->tm_hour = time2->tm_hour - 5;
	time2->tm_min = time2->tm_min - 30;

	strftime(timestring,
		20,
		"%H:%M:%S",
		time2);
	printf("Time2: %s\n",
		timestring);

	free(time2);
	return(0);
}

And the output is,

Time1: 05:30:00
Time2: 05:31:10

I don’t know why its happening, ‘localtime()’ creates ‘struct tm’ structure which by default have 05:30:00 as its starting time. I need to manually subtract the 5 from tm_hour and 3 from tm_min to get what I want.

	time1.tm_hour = time1.tm_hour - 5;
	time1.tm_min = time1.tm_min - 30;

	time2->tm_hour = time2->tm_hour - 5;
	time2->tm_min = time2->tm_min - 30;

Here is the updated output,

Time1: 00:00:00
Time2: 00:01:10

Also ‘localtime()’ sets default values to all the variables in the result ‘struct tm’ structure. google not helping to find the reason.

Advertisements

2 thoughts on “‘localtime()’ loves ’05:30:00′

  1. localtime() is used to convert UNIX time in seconds since epoch to a tm structure, but it takes the timezone into account! This means you’re probably using the timezone UTC+5:30 on your system.

    You can use gmtime() to convert your values assuming UTC+0.

  2. Thank you so much for the clarification. I should have been looked into the manuals atleast once, they are clearly saying about ‘localtime()’. But my linux box doesn’t have any manuals for section(3). Linux needs to improve in this place.

    Anyway, Now I have my own script to get manuals :) take a look at this script, https://mohan43u.wordpress.com/2009/06/01/freebsdman

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s