Using C, I want to convert a UNIX Timestamp number to several usual date data.
How do I convert a UNIX timestamp like 12997424 to different numbers representing seconds, minutes, hours and days while using C?
Use gmtime or localtime from standard library. Prototypes are defined in time.h.
ADDED & EDITED:
So for example, the following code prints current timestamp, hour and minute:
#include <stdio.h>
#include <time.h>
void main() {
time_t t;
struct tm ttm;
t = time(NULL);
printf("Current timestamp: %d\n", t);
ttm = * localtime(&t);
printf("Current time: %02d:%02d\n", ttm.tm_hour, ttm.tm_min);
}
Here's an example of how to use localtime to convert time_t to tm as local time (credit goes to www.cplusplusreference.com):
#include <stdio.h>
#include <time.h>
int main() {
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
printf ("Current local time and date: %s", asctime(timeinfo));
return 0;
}
Related
I am working on an Linux based router. I am working on a C application. I want to get current time in my application continuously.
The problem is, it gives me time according to the application launch timezone although I have changed timezone after the application started. The timezone of the system has been changed. The date command on Linux terminal shows different timezone and date/time.
time_t currTm;
struct tm *loctime;
char udrTime[50];
while (1)
{
currTm = time(NULL);
loctime = localtime(&currTm);
strftime(udrTime, sizeof(udrTime), "%Y-%m-%d %H:%M:%S", loctime);
printf("udr_time = %s\n", udrTime);
usleep(10000);
}
I expect output according to timezone changes.
To change the timezone from within the application just set TZ environment variable, nothing else is necessary:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
void print_time(time_t t) {
char buf[256];
strftime(buf, sizeof buf, "%H:%M:%S", localtime(&t));
printf("%s %s\n", getenv("TZ"), buf);
}
int main() {
time_t t = time(NULL);
setenv("TZ", "Europe/London", 1);
print_time(t);
setenv("TZ", "America/New_York", 1);
print_time(t);
return 0;
}
Outputs:
Europe/London 15:48:58
America/New_York 10:48:58
In shell scripting, when ever I want the local time I do something like
date +%s
from the command line and it returns me the current date and time in this format "1343221713"
I am wondering whether there is a way to achieve the same result in C
Use time.h library in C
example:
#include <stdio.h>
#include <time.h>
int main()
{
/* Obtain current time as seconds elapsed since the Epoch. */
time_t clock = time(NULL);
/* Convert to local time format and print to stdout. */
printf("Current time is %s", ctime(&clock));
return 0;
}
see more examples:
http://en.wikipedia.org/wiki/C_date_and_time_functions
More flexible than time(3) is gettimeofday(3) as declared in sys/time.h
#include <sys/time.h>
#include <stdio.h>
int main(void)
{
struct timeval tv = {0};
gettimeofday(&tv, NULL);
printf("seconds since epoch %ld, microseconds %ld\n", tv.tv_sec, tv.tv_usec);
return 0;
}
I am wondering is there any function that would return the current time in seconds, just 2 digits of seconds? I'm using gcc 4.4.2.
The following complete program shows you how to access the seconds value:
#include <stdio.h>
#include <time.h>
int main (int argc, char *argv[]) {
time_t now;
struct tm *tm;
now = time(0);
if ((tm = localtime (&now)) == NULL) {
printf ("Error extracting time stuff\n");
return 1;
}
printf ("%04d-%02d-%02d %02d:%02d:%02d\n",
tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
return 0;
}
It outputs:
2010-02-11 15:58:29
How it works is as follows.
it calls time() to get the best approximation to the current time (usually number of seconds since the epoch but that's not actually mandated by the standard).
it then calls localtime() to convert that to a structure which contains the individual date and time fields, among other things.
at that point, you can just de-reference the structure to get the fields you're interested in (tm_sec in your case but I've shown a few of them).
Keep in mind you can also use gmtime() instead of localtime() if you want Greenwich time, or UTC for those too young to remember :-).
A more portable way to do this is to get the current time as a time_t struct:
time_t mytime = time((time_t*)0);
Retrieve a struct tm for this time_t:
struct tm *mytm = localtime(&mytime);
Examine the tm_sec member of mytm. Depending on your C library, there's no guarantee that the return value of time() is based on a number of seconds since the start of a minute.
You can get the current time with gettimeofday (C11), time (Linux), or localtime_r (POSIX); depending on what calendar & epoch you're interested. You can convert it to seconds elapsed after calendar epoch, or seconds of current minute, whichever you are after:
#include <stdio.h>
#include <string.h>
#include <time.h>
int main() {
time_t current_secs = time(NULL);
localtime_r(¤t_secs, ¤t_time);
char secstr[128] = {};
struct tm current_time;
strftime(secstr, sizeof secstr, "%S", ¤t_time);
fprintf(stdout, "The second: %s\n", secstr);
return 0;
}
You want to use gettimeofday:
man 2 gettimeofday
#include <stdio.h>
#include <sys/time.h>
int main (int argc, char **argv)
{
int iRet;
struct timeval tv;
iRet = gettimeofday (&tv, NULL); // timezone structure is obsolete
if (iRet == 0)
{
printf ("Seconds/USeconds since epoch: %d/%d\n",
(int)tv.tv_sec, (int)tv.tv_usec);
return 0;
}
else
{
perror ("gettimeofday");
}
return iRet;
}
This is better to use then time(0), because you get the useconds as well, atomically, which is the more common use case.
I represent dates using seconds (and microseconds) since 1970 as well as a time zone and dst flag. I want to print a representation of the date using strftime, but it uses the global value for timezone (extern long int timezone) that is picked up from the environment. How can I get strftime to print the zone of my choice?
The following program sets the UNIX environment variable TZ with your required timezone and then prints a formatted time using strftime.
In the example below the timezone is set to U.S. Pacific Time Zone .
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (int argc, char *argv[])
{
struct tm *mt;
time_t mtt;
char ftime[10];
setenv("TZ", "PST8PDT", 1);
tzset();
mtt = time(NULL);
mt = localtime(&mtt);
strftime(ftime,sizeof(ftime),"%Z %H%M",mt);
printf("%s\n", ftime);
}
Change timezone via setting timezone global variable and use localtime to get the time you print via strftime.
Jon Skeet spoke of the complexity of programming dates and times at the 2009 DevDays in London.
Can you give me an introduction to the ANSI C date/time functions on UNIX and indicate some of the deeper issues I should also consider when using dates and times?
Terminology
A date/time can be in two formats:
calendar time (a.k.a. simpletime) – time as an absolute value typically since some base time, often referred to as the Coordinated Universal Time
localtime (a.k.a. broken-down time) – a calendar time made up of components of year, month, day etc. which takes into account the local time zone including Daylight Saving Time if applicable.
Data types
The date/time functions and types are declared in the time.h header file.
Time can be stored as a whole number or as an instance of a structure:
as a number using the time_t arithmetic type – to store calendar time as the number of seconds elapsed since the UNIX epoch January 1, 1970 00:00:00
using the structure timeval – to store calendar time as the number of seconds and nanoseconds elapsed since the UNIX epoch January 1, 1970 00:00:00
using the structure tm to store localtime, it contains attributes such as the following:
tm_hour
tm_min
tm_isdst
The tm_isdst attribute above is used to indicate Daylight Saving Time (DST). If the value is positive it is DST, if the value is 0 it is not DST.
Program to print the current Coordinated Universal Time
#include <stdio.h>
#include <time.h>
int main ( int argc, char *argv[] )
{
time_t now;
now = time ( NULL );
printf ( "It’s %ld seconds since January 1, 1970 00:00:00", (long) now );
return 0;
}
In the program above the function time reads the UNIX system time, subtracts that from January 1, 1970 00:00:00 (the UNIX epoch) and returns its result in seconds.
Program to print the current local time
#include <stdio.h>
#include <time.h>
int main ( int argc, char *argv[] )
{
time_t now;
struct tm *lcltime;
now = time ( NULL );
lcltime = localtime ( &now );
printf ( "The time is %d:%d\n", lcltime->tm_hour, lcltime->tm_min );
return 0;
}
In the program above the function localtime converts the elapsed time in seconds from the UNIX epoch into the broken-down time. localtime reads the UNIX environment TZ (through a call to the tzset function) to return the time relative to the timezone and to set the tm_isdst attribute.
A typical setting of the TZ variable in UNIX (using bash) would be as follows:
export TZ=GMT
or
export TZ=US/Eastern
Program to print the current formatted Greenwich Mean Time
#include <stdio.h>
#include <time.h>
int main ( int argc, char *argv[] )
{
time_t now;
struct tm *gmt;
char formatted_gmt [50];
now = time ( NULL );
gmt = gmtime ( &now );
strftime ( formatted_gmt, sizeof(formatted_gmt), "%I:%M %p", gmt );
printf ( "The time is %s\n", formatted_gmt );
return 0;
}
In the program above the function strftime provides specialised formatting of dates.
Other issues to consider
Leap seconds
What should we do to prepare for 2038?