I have written the following code to convert date to timestamp.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main()
{
struct tm date_time;
char date_time_buf[255];
char date_time_hdr[255]={0};
strncpy(date_time_hdr,"Thu, 02 Mar 2017 05:54:28 GMT",255);
memset(&date_time, 0, sizeof(struct tm));
strptime(date_time_hdr, "%a, %d %b %Y %H:%M:%S %Z", &date_time);
memset(date_time_buf, 0, 255);
strftime(date_time_buf, 255, "%s", &date_time);
int p=atoi(date_time_buf);
printf("time is %d \r\n", p);
return 0;
}
I am able to convert date to timestamp. But facing an issue.
The timestamp is offset by 5 hrs 30 minutes which is the timezone of my linux machine. But I don't want that. Is there a way to ignore system timezone?
Instead of using strftime() to format the broken down time struct tm as an integer, and parsing it using atoi(), you can use the simple but nonstandard timegm() function.
Even though timegm() is not in POSIX, it is provided by most POSIXy systems. If you want your code to be portable across POSIXy systems, you can use a workaround (as described in some versions of the timegm man page):
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
time_t alt_timegm(struct tm *from)
{
char *tz;
time_t result;
int saved_errno;
tz = getenv("TZ");
if (tz)
tz = strdup(tz);
setenv("TZ", "", 1); /* TZ empty refers to UTC */
tzset();
errno = 0;
result = mktime(from);
saved_errno = errno;
setenv("TZ", tz, 1);
free(tz);
errno = saved_errno;
return result;
}
This workaround does have the drawback that it temporarily modifies the current timezone, which affects other threads executing any timezone-related functions. In a single-threaded process this is not an issue (as the timezone-related functions are not async-signal safe, so they aren't to be used in signal handlers).
In multithreaded programs, one should serialize all accesses to the timezone related functions -- alt_timegm() above, mktime(), localtime(), and so on --, to ensure each function is run with the proper timezone set.
The timegm() implementations in Linux and BSDs are thread-safe; that is, they do not modify the timezone.
Using the above, parsing a string using an strptime() format to an Unix timestamp is easy:
const char *parse_utc(const char *s, const char *format, time_t *to)
{
char *result;
struct tm t_parts;
time_t t;
if (!s || !format) {
errno = EINVAL;
return NULL;
}
result = strptime(s, format, &t_parts);
if (!result) {
errno = EINVAL;
return NULL;
}
errno = 0;
t = alt_timegm(&t_parts);
if (to)
*to = result;
return (const char *)result;
}
The above parse_utc() parses a string s using strptime() format format, saving the UTC timestamp to to if not NULL, returning the pointer to the first unparsed character in string s.
Setting errno = 0 in the above functions may look strange, but it is because the mktime() (and timegm()) function may or may not set errno in case of an error; it just returns (time_t)-1. This means that it is impossible to reliably determine whether a (time_t)-1 (corresponding to last second of year 1969 in UTC`) is an actual valid timestamp, or an error return.
In other words, if errno != 0 after a call to parse_utc(), there was an error. (Note that if the string or format was invalid, parse_utc() returns NULL, with errno == EINVAL.) If errno == 0 but *to == (time_t)-1, it depends on the architecture whether the time string actually referred to the last second of year 1969 in UTC, or if it was an error; we simply do not know.
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
I am implementing a version of ls -la command in OS X. I happened to notice that ls command lists years for some files and times for others as shown below:
-rwxr-xr-x 1 Jenna 197609 3584 Mar 13 2015 untitled1.exe*
drwxr-xr-x 1 Jenna 197609 0 Mar 2 07:48 Videos/
After some research, I found out that files older than 6 months gets a year while those that are not get the actual time. How do I get the date and times of these files to correctly display either the year or time ? Currently I have the following code which always displays the time:
int main()
{
struct stat *fileInfo;
char dir[] = "~/Desktop/file.txt";
stat(dir, &fileInfo);
printf("%.12s ", 4+ctime(&fileInfo->st_mtimespec));
return 0;
}
strftime is your friend here. Formatting it like ls is not that straight forward. The two formats that ls in coreutils is using are
"%b %e %Y"
"%b %e %H:%M"
Heres one paragraph from the docs of the ls in coreutils
/* TRANSLATORS: ls output needs to be aligned for ease of reading,
so be wary of using variable width fields from the locale.
Note %b is handled specially by ls and aligned correctly.
Note also that specifying a width as in %5b is erroneous as strftime
will count bytes rather than characters in multibyte locales. */
N_("%b %e %H:%M")
They're taking into consideration things like Locale ie multibyte characters etc. They also discuss things like when a file is older than N months they change how it's displayed etc. You can find a lot of information here...
http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/ls.c
For your needs something simpler might be fine, heres some code that might point you in the correct direction. You can change the format to whatever you want by changing the third argument to strftime.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(void) {
time_t t;
srand((unsigned) time(&t));
size_t i = 0;
struct timespec ttime;
while(i < 0xffffffff) {\
ttime.tv_sec = i;
i += 3600;
struct tm time_struct;
localtime_r(&ttime.tv_sec, &time_struct);
char time_str[1024];
if(rand() > RAND_MAX/2) {
strftime(time_str, sizeof(time_str), "a == %b %e %Y", &time_struct);
}
else {
strftime(time_str, sizeof(time_str), "b == %b %e %H:%M", &time_struct);
}
printf("%s\n", time_str);
}
exit(0);
}
Try it and see what it does. From the man page, tweaking it will get you really close to what you need.
size_t strftime(char *restrict s, size_t maxsize, const char *restrict format, const struct tm *restrict timeptr);
The strftime() function formats the information from timeptr into the
buffer s, according to the string pointed to by format.
If I recall correctly, the determining factor used by ls -l to output a date/time or output a date/year is whether the mtime year returned by stat matches the current year. If the file mtime year matches the current year, then date/time information is provided, if the mtime year is not the current year, then date/year information is provided.
In order to make the comparison, you need to fill a struct tm for both the file mtime and now. The following example uses localtime_r to fill each struct tm, makes the comparison, and then outputs the file details accordingly.
(the code will read/compare mtimess and output the time format for all filenames provided as arguments. (a placeholder string is used to provide basic formatting for the file permissions, number, user, group, size, etc.)
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#define MAXC 64
void dump_tm (struct tm *t);
int main(int argc, char **argv)
{
int i = 0;
char time_str[MAXC] = "";
time_t now = time (NULL);
struct stat sb;
struct tm tmfile, tmnow;
if (argc < 2) { /* validate sufficient arguments provided */
fprintf (stderr, "error: insufficient input, usage: %s <pathname>\n",
argv[0]);
return 1;
}
for (i = 1; i < argc; i++) { /* for each file given as arg */
if (stat(argv[i], &sb) == -1) { /* validate stat of file */
perror("stat");
return 1;
}
localtime_r (&sb.st_mtime, &tmfile); /* get struct tm for file */
localtime_r (&now, &tmnow); /* and now */
if (tmfile.tm_year == tmnow.tm_year) { /* compare year values */
strftime (time_str, sizeof (time_str), "%b %e %H:%M",
&tmfile); /* if year is current output date/time */
printf ("permission 1 user group 12345 %s %s\n",
time_str, argv[i]);
}
else { /* if year is not current, output time/year */
strftime (time_str, sizeof (time_str), "%b %e %Y",
&tmfile);
printf ("permission 1 user group 12345 %s %s\n",
time_str, argv[i]);
}
}
return 0;
}
Example ls -l Output
$ ls -l tmp.c ls_time_date_fmt.c
-rw-r--r-- 1 david david 1312 Apr 6 03:15 ls_time_date_fmt.c
-rw-r--r-- 1 david david 2615 May 23 2014 tmp.c
Program Use/Output
$ ./bin/ls_time_date_fmt ls_time_date_fmt.c tmp.c
permission 1 user group 12345 Apr 6 03:15 ls_time_date_fmt.c
permission 1 user group 12345 May 23 2014 tmp.c
Let me know if you have any questions.
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 can get the system time using struct tm and time(),localtime(),asctime().but i need help about how i can set time of system using c program.
if you don't want to execute a shell command you can (as you mentioned) use the settimeofday, i would start by reading the MAN page, or looking for some examples
here's an example:
#include <sys/time.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[])
{
struct timeval now;
int rc;
now.tv_sec=866208142;
now.tv_usec=290944;
rc=settimeofday(&now, NULL);
if(rc==0) {
printf("settimeofday() successful.\n");
}
else {
printf("settimeofday() failed, "
"errno = %d\n",errno);
return -1;
}
return 0;
}
Shamelessly ripped From IBMs documentation, the struct timeval struct holds the number of seconds (as a long) plus the number of microseconds (as a long) from 1 January 1970, 00:00:00 UTC (Unix Epoch time). So you will need to calculate these numbers in order to set the time. you can use these helper functions, to better handle dealing with the timeval struct.
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.