getting system date(int & char mixed) using sscanf - c

I am trying to include system date in a program, which would calculate the total value of days since 2000. So that I could compare values of various dates (like- Antivirus update date, OS updation date) with it in order to find what is the delay in system updation. The procedure of finding date in C was killing me so I used system command to find out the current date.
system("date/t > system_date.txt");
I want to read the date from this file. There was no problem if the date was all in digits(ex.- 03/09/13). But the date displayed from DOS is of type : 03-Sep-13 . If I use sscanf as follows:
FILE *fp_date=fopen("system_date.txt","r");
char buffer[11]; int day,yr; char yr[3];
fgets(buffer,11,fp_date);
sscanf("%d-??????-%d",&day,&mon,&yr);
Now how do I scan these separately with their data types? I don't know what to use in place of ??????. Or the other method which I have been using is to store whole line in an array, then run for loops to get elements separated by '-'. But I just wanted to be a bit more sophisticated. Thanks...

You don't need system (and not even the date command). BTW, using popen("date","r") might be simpler but is still not the right way.
Read first the time(7) man page.
Then use code like
time_t now=0;
time (&now);
struct tm* ltm = localtime(&now);
The time(2) syscall gives the time from the Unix epoch (start of 1970 year) in seconds. Use clock_gettime(2) if you want more precision (or measure CPU, or thread, time). gettimeofday(2) is becoming obsolete. localtime(3) converts a Unix time to a struct tm containing seconds, minutes, ... day of week, day of month, month, .... fields. Use mktime for the opposite conversion of a struct tm to a time_t. And time_t is also given by other functions or syscalls (like stat(2) giving metadata about a file, including its modification time).
You can use fields from ltm programmatically like ltm->tm_sec for seconds, ltm->tm_min for minutes, .... ltm->tm_monfor month (0 for January, etc...), etc....
If you want a string, use strftime(3) like
char timebuf[32];
strftime (timebuf, sizeof(timbuf), "%d %b %Y", ltm);
The opposite function is strptime(3) which parses a string into a struct tm.
Notice that strftime use localization (see locale(7) first). So your user could get a french abbreviated month from %b (if his system is localized for French).
If you want universal (so called GMT) time, use gmtime instead of localtime. In multithreaded programs use localtime_r a,d gmtime_r and give them your own struct tm.

Don't do this. Obtaining the current date/time in C is trivial:
#include <time.h>
/* ... */
struct tm *tm = localtime(time(0));
The way you're trying to do it is much harder, not to mention error-prone. (For example, what happens if two instances run at the same time and both try to write to the same file?) In general, system is always the wrong way to do something.

Don't do that. Just use time(2) (C89) or gettimeofday(3) (POSIX) to get the current system time in Unix time format. If you need to convert that to other forms like a string representation or a struct tm object, then you can use various conversion functions such as ctime(3), gtime(3), and localtime(3).
#include <time.h>
time_t now = time(NULL);
printf("The current time is: %s\n", ctime(&now)); // Warning: not thread-safe
struct tm *now_tm = localtime(now); // Warning: not thread-safe
printf("Year=%d month=%d day=%d\n hour=%d minute=%d second=%d",
1900 + now_tm->tm_year,
1 + now_tm->tm_mon,
now_tm->tm_mday,
now_tm->tm_hour,
now_tm->tm_min,
now_tm->tm_sec);

Related

Getting Abbreviated timezone using strftime() using C

I have viewed this, and this, on SO, but they deal with non-C variations of the same problem.
Using GNU GCC compiler (Code::Blocks, in Windows) with the following code:
int main(void)
{
time_t rawtime;
struct tm *info;
char timeStr[80];
time( &rawtime );
info = localtime( &rawtime );
strftime(timeStr,80,"%a %b %d %H:%M:%S %Z %Y", info);
printf("%s", timeStr);
getchar();
return 0;
}
I am getting this time string:
Tue Aug 30 14:55:08 Pacific Daylight Time 2016
Everything is fine except time zone. I prefer it to be abbreviated, such as:
Tue Aug 30 14:55:08 PDT 2016
In every man page, or windows documentation for strftime() I can find the description for the format specifier %Z goes something like: Timezone name or abbreviation. ( eg. here. )
What is the trick to formatting timezone to be abbreviated?
strftime gives no guarantee whether you'll get the full name or the abbreviation. It is implementation dependent. The C99 spec (and Microsoft's documentation) says:
%Z is replaced by the locale’s time zone name or abbreviation, or by no characters if no time zone is determinable.
AFAIK there is no standard C way to guarantee you'll get the time zone abbreviation. That assumes you use the system time zone database. You could ship with your own copy of the time zone database.
In general, time zone abbreviations are a bad idea because they're ambiguous. Skimming the list we find ACT, AMT, BST, ECT, GST, IST, LHST, MST, PST, and SST are all ambiguous. You're better off using the full name, the numeric offset (ie. %z), or eschew time zones altogether and use UTC (particularly useful for logging).
I recently needed the same thing, and determined that there is No Good Answer. I wrote some brute-force code to map Windows timezone strings like "Eastern Standard Time" to "EST", but I knew that (a) this was a Bad Idea and (b) my list of translations would never be complete.

Convert time_t to tm in a particular timezome

The localtime_r function converts a time_t timestamp to a struct tm in the current timezone.
How can you convert a UTC time_t to a struct tm in a different timezone, e.g. to the time in, say, Sydney Australia, taking into account daylight savings and whatever else, and without affecting uses of localtime in other parts of the program?
NetBSD's C runtime library includes some functions to deal with arbitrary timezones (see NetBSD 6.1.5 - man page for ctime (netbsd section 3). To get similar functions in other projects, you can use code from IANA's Time Zone Database, particularly, its localtime.c, private.h and tzfile.h files.

How Do You Get The Last Access Time Of A File In Epoch In C?

I'm trying to get the last access time of a file in epoch format in C but I can't figure out an easy way to do so. I know you can get the last access/last modified time of a file with stat() and then using st_atime but that returns the time back in a nice human readable format. Is there any way to return the time back in epoch format?
That's puzzling; the value returned by stat() in st_atime is a time in seconds since The Epoch (1970-01-01 00:00:00 +00:00). It is not neatly formatted; you have to dissect it, probably with localtime() or gmtime() or one of the re-entrant variants of those functions, and then format it with one of the other time formatting functions (ctime(), asctime() or, better, strftime()).

Get date from specific timezone - C

I need to get the date/time from a specific timezone without setting the TZ variable.
I tried to use the gmtime and plus to the hour the difference, the issue I got with this method, is that time variations, for example, the daylight, or the day difference between China/Usa caused by the hour, I need to handle all of that, is there any way/library or whatever I can use for get an specific timezone with that variations included?
I am using win32, It would be better if it works with everything. Thanks!
The best way to do this (if I'm understanding your requirement correctly) is to use the Olson/IANA TZ database. The Wikipedia article points to the IANA sources.
Using this library isn't a one-liner (though depending on your platform, the library may be already installed or be easily-installable). However (a) it's the Right Thing To Do, (b) it's as robust and accurate as anything else you're likely to find, and (c) it's well enough known that I expect you'll have little difficulty in googling for information and tutorials about it, should you need to.
Perhaps localtime() will work for you.
#include <stdio.h> /* puts, printf */
#include <time.h> /* time_t, struct tm, time, localtime */
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
printf ("Current local time and date: %s", asctime(timeinfo));
return 0;
}

How to determine if daylight saving time is active in C?

I have a C application running on cross platforms. In this program, I need to write a function which determines if the given date is DST or not.
Actually, i try to find DST begin-DST end dates in pure C. Is there any simple and standard way to do this?
time.h provides tm structs with a tm_isdst flag. Use time to get the current time, localtime to get a tm struct with the time adjusted to the current locale and read the tm_isdst flag.
From the manpage:
tm_isdst A flag that indicates whether daylight saving time is in effect at the
time described. The value is positive if daylight saving time is in effect, zero
if it is not, and negative if the information is not available.
The code is:
time_t rawtime;
struct tm timeinfo; // get date and time info
time(&rawtime);
localtime_s(&timeinfo, &rawtime);
int isdaylighttime = timeinfo.tm_isdst;
Implementation is not allowed to assume that tm_isdst is always 0.
It must provide correct data.
If implementation cannot provide tm_isdst which is consistent with rules set in a country than it should set tm_isdst to negative value as specified in 7.23.1/4 in the same Standard.

Resources