c time formattings - c

How do I format a time_t structure to something like this year-month-day h:m:s,
I have already tried using ctime:
time_t t = time((time_t*) NULL);
char *t_format = ctime(&t);
but it doesn't give me the desired results
example :
2011-11-10 10:25:03. What I need is a string containing the result so I can write it to a file. Thanks

Use strftime from time.h like so:
char tc[256];
strftime(tc, 256, "%Y-%m-%d %H:%M:%S", tm);

http://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html

Related

What function in C can I use to get the date alone separate from time?

I am building a C program and I need to use time separately and also the date separately. I want to do this without using the structure struct tm since I have to send the time and the date to different columns in my database table called Logs:
int main(){
duration = clock() - duration;
double Duration = ((double)duration)/CLOCKS_PER_SEC;
char* IPaddr = inet_ntoa(newAddr.sin_addr);
int PortNo = ntohs(newAddr.sin_port);
printf("\n%s %s %d %f\n", task, IPaddr, PortNo, Duration);
printf("now: %d-%d-%d %d:%d:%d\n",tm.tm_mday,tm.tm_mon+1,tm.tm_year+1900,tm.tm_hour,tm.tm_min,tm.tm_sec);
if (mysql_query(con, "INSERT INTO Logs(ClientIP, ClientPort, Job_type, SubmissionTime, SubmissionDate, Duration)
VALUES(%s, %d, %s, %, %, %f)")) {
finish_with_error(con);
}
return 0;
}
You might want to declare two character arrays, one for the date string and one for the time string, and call strftime twice to construct them.
Something like this:
char SubmissionDate[20], SubmissionTime[20];
strftime(SubmissionDate, sizeof(SubmissionDate), "%Y-%m-%d", &tm);
strftime(SubmissionTime, sizeof(SubmissionTime), "%H:%M:%S", &tm);

How can I create an OID from time

In pymongo you can do something like this to create an OID from time:
dummy_id = ObjectId.from_datetime(time)
Is there something like that in mongoc?
I saw that there's a "bson_oid_get_time_t()" function, but is there a reverse function of this, and if not, How can it be implemented in C?
I don't believe there is a reverse function, but it should be easy for you to generate your own using the default constructor and "fixing" the time.
Here is an example where I create an object ID.
Then I create a timestamp for December 25, 2014 and modify the OID to that date.
#include <time.h>
#include <bson.h>
int
main (int argc,
char *argv[])
{
time_t oid_thinks_time; //what time does the OID think it is
bson_oid_t oid;
bson_oid_t *oid_pointer = &oid;
bson_oid_init (&oid, NULL); // get a standard ObjectId
oid_thinks_time = bson_oid_get_time_t (&oid); //It was just made
printf ("The OID was generated at %u\n", (unsigned) oid_thinks_time); //prove it
time_t ts = time(NULL); //make a new time
struct tm * timeinfo = localtime(&ts);
timeinfo->tm_year = 2014-1900; //-1900 because time.h
timeinfo->tm_mon = 12 - 1; // time.h off by one (starts at 0)
timeinfo->tm_mday = 25;
ts = mktime(timeinfo); // create the time
u_int32_t ts_uint = (uint32_t)ts;
ts_uint = BSON_UINT32_TO_BE (ts_uint); //BSON wants big endian time
memcpy (&oid_pointer->bytes[0], &ts_uint, sizeof (ts_uint)); //overwrite the first 4 bytes with user selected time
oid_thinks_time = bson_oid_get_time_t (&oid);
printf ("The OID was fixed to time %u\n", (unsigned) oid_thinks_time);//prove it
}
The output of this code is:
The OID was generated at 1491238015
The OID was fixed to time 1419526015

Adding time and date to a filename

I'm trying to write a source file, that would take in the filename/directory and then add current date & time to the end of the file name. So far I've found out that we can use the time() & localtime() functions. However, I'm not quite sure on where to start.
Could someone give me some instructions/steps on the path I could follow to get there?
Thanks! :D
Use time() and localtime() to get the current time
Use strftime() to format it to the format you want.
Use snprintf() to combine the formatted time with the original file name.
Use rename() to do the actual renaming.
Note that all of the above can be done in one line of shell script, so ask yourself whether you really need to do it in C, as opposed to relegating it to sh.
To get the date/time you have to include time.h.
Then you can use the localtime function like this:
time_t t = time(NULL);
struct tm tm = *localtime(&t);
The struct tm contains the desired information. You can access the day of the month by tm.tm_mday and so on.
You can use sprintf to write all the date information to a string like this:
char datum[128];
sprintf(datum, "%d-%d-%dT%d:%d:%d", tm.tm_year+1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
printf("%s\n", datum);
would give something like
2013-10-31T20:26:42
You can append this string to your filename by using strcat
This code will work.
char timestr[50];
time_t now = time(NULL);
struct tm *t = localtime(&now);
strftime(timestr, sizeof(timestr)-1, "%m-%d-%Y", t);
timestr[49] = 0;
if((filename = malloc(strlen(argv[2])+strlen(timestr)+1) != NULL) {
filename[0] = '\0';
strcat(filename,argv[2];
strcat(filename,"_");
strcat(filename,timestr);
strcat(filename,".log");
}
Just change the argv[2] as per your code argc.

How tm structures (from time.h) works?

I need to create a struct where is set a date. I googled something and i found the tm structure from the library time.h, but I'm having some troubles;
I need to print some dates on a log file, here an example:
typedef struct tm* tm_;
...
void NEW_Job()
{
time_t t;
tm_ secs;
t=time(NULL);
secs=localtime(&t);
add_QUEUEnode(generate_job());
fprintf(f, "\n%d:%d.%d : New job created.", secs->tm_hour, secs->tm_min, secs->tm_sec);
}
I really don't know where i'm wrong.
Thanks in advance for the help :)
The exact error wasn't there, but in another line of the code, exactly here:
void PCunload(int b)
{
time_t t;
tm_ secs;
int hh, mm, ss;
hh=(time(NULL)-n[b].start_time)/3600;
mm=((time(NULL)-n[b].start_time)%3600)/60;
ss=((time(NULL)-n[b].start_time)%3600)%60;
t=time(NULL);
secs=localtime(&t);
n[b].job.priority=-1;
-->>fprintf(f, "\n%d:%d.%d : PC number %d unloaded; elapsed time: %d:%d.%d", secs->tm_hour, secs->tm_min, secs->tm_sec, hh, mm, ss);
}
There I tried to do the conversion inside the printf functions, but something goes wrong...
My apologies!
strftime() can help you printing date and time at your favorite format. Please take a look at man strftime.

C - putting current date in a filename

I have 4 values: A,B,C,D. After doing a set of computations with those values, I want my code to output the results in a file of the form ABCD_MM.DD.YY.txt, to keep track of when it was done.
I'm not quite sure on the best way to do this in C. I have a "working" version using itoa(), which isn't a standard C function and will go (and has gone) unrecognized on machines other than mine when compiling.
This is the code I have for doing this, could someone help with a better (and universally accepted) way? The char array name was defined with a global scope.
void setFileName(){
time_t now;
struct tm *today;
char date[9];
//get current date
time(&now);
today = localtime(&now);
//print it in DD.MM.YY format.
strftime(date, 15, "%d.%m.%Y", today);
char buff[20];
char vars[20];
//put together a string of the form:
//"ABCD_DD.MM.YY.txt"
strcpy(vars, itoa(A, buff, 20));
strcat(vars, itoa(B, buff, 20));
strcat(vars, itoa(C, buff, 20));
strcat(vars, itoa(D, buff, 20));
strcpy(name, vars);
strcat(name, "_");
strcat(name, date);
strcat(name, ".txt");
}
char filename [ FILENAME_MAX ];
snprintf(filename, FILENAME_MAX, "%d%d%d%d_%s.txt", A, B, C, D, date);

Resources