fprintf and ctime without passing \n from ctime - c

I have an issue with inserting time in a text file. I use the following code and i get |21,43,1,3,10,5| Wed Feb 01 20:42:32 2012 which is normal but what i WANT TO DO is place the time before the numbers for example like Wed Feb 01 20:42:32 2012 |21,43,1,3,10,5| However, i cant do so cause when i use the fprintf with ctime function before fprintf the numbers it recognizes the \n within ctime and so it changes line 1st and then printing the numbers. It goes like:
Wed Feb 01 20:42:32 2012
|21,43,1,3,10,5|
which is something that i dont want... How can i fprintf the time without swiching to the next line in the text??? Thanks in advance!
fprintf(file," |");
for (i=0;i<6;i++)
{
buffer[i]=(lucky_number=rand()%49+1); //range 1-49
for (j=0;j<i;j++)
{
if (buffer[j]==lucky_number)
i--;
}
itoa (buffer[i],draw_No,10);
fprintf(file,"%s",draw_No);
if (i!=5)
fprintf(file,",");
}
fprintf(file,"| %s",ctime(&t));

You can use a combination of strftime() and localtime() to create a custom formatted string of your timestamp:
char s[1000];
time_t t = time(NULL);
struct tm * p = localtime(&t);
strftime(s, 1000, "%A, %B %d %Y", p);
printf("%s\n", s);
The format string used by ctime is simply "%c\n".

You can use strtok() to replace \n with \0. Here's a minimal working example:
#include <stdio.h>
#include <string.h>
#include <time.h>
int main() {
char *ctime_no_newline;
time_t tm = time(NULL);
ctime_no_newline = strtok(ctime(&tm), "\n");
printf("%s - [following text]\n", ctime_no_newline);
return 0;
}
Output:
Sat Jan 2 11:58:53 2016 - [following text]

Just use %.19s :
struct timeb timebuf;
char *now;
ftime( &timebuf );
now = ctime( &timebuf.time );
/* Note that we're cutting "now" off after 19 characters to avoid the \n
that ctime() appends to the formatted time string. */
snprintf(tstring, 30, "%.19s", now); // Mon Jul 05 15:58:42

Copy the return of ctime() to a temporary string, remove the '\n' from that temporary string, then print the temporary string.
Print just the 1st 24 characters of the return from ctime() by using the (field width and) precision of the printf conversion.

in c++11 you can do it like this:
#include <iostream>
#include <chrono>
#include <iomanip>
using namespace std;
using namespace chrono;
// Prints UTC timestamp
void printTime() {
time_point<system_clock> now = system_clock::now();
time_t now_time = system_clock::to_time_t(now);
auto gmt_time = gmtime(&now_time);
auto timestamp = std::put_time(gmt_time, "%Y-%m-%d %H:%M:%S");
cout << timestamp << endl;
}
Output:
2017-06-05 00:31:49

How about:
char *p;
int len;
/* ... */
p = ctime(&t);
len = strlen(p);
fprintf(file,"| %.*s", len - 1, p);
That way it only prints the string minus the last character (i.e. the \n).

I did this after obtaining the ctime string:
#include <string.h>
...
myctime[ strlen(myctime) - 1 ] = '\0';
This just overwrites the ctime carriage return with a string termination character, effectively terminating the string with two '\0' characters instead of one. (It seems weird that ctime does that in the first place.)

Just copy 'length - 1' bytes to another string.
strncpy( newString, draw_No, strlen(draw_no) - 1 );

Simply:
c_time_string = ctime(&current_time);
len_of_new_line = strlen(c_time_string) - 1;
c_time_string[len_of_new_line] = '\0';
What this will actually do is it replaces strlen - 1 char (new line char in this case) of ctime array with null-terminator character - it cuts out new line character from end '\n' and shorten array of 1 character.
If strlen was 25 before, after this it should be 24.

Related

Why doesn't strptime() set tm_wday properly in this example?

I'm using strptime(3) to parse a string representing a date:
#include <time.h>
#include <stdio.h>
int main () {
struct tm t;
strptime("2015-04-19 12:00:00", "%F %T", &t); /* Sunday */
printf("%d\n", t.tm_wday); /* Should print 0 */
return 0;
}
That date is a Sunday, according to the output of cal -y 2015. But when I compile this on OSX (presumably with clang) it prints 6:
$ gcc timetest.c ; ./a.out
6
whereas on Debian it prints the (correct) 0:
$ gcc timetest.c ; ./a.out
0
Any explanation for the difference?
UPDATE
Here is the same program, except that t is initialised with a valid time and I'm reporting the return value of strptime():
#include <time.h>
#include <stdio.h>
int main () {
time_t epoch = 0;
struct tm t;
char *ret;
t = *localtime(&epoch);
ret = strptime("2015-04-19 12:00:00", "%F %T", &t); /* Sunday */
printf("%d\n", t.tm_wday); /* Should print 0 */
printf("strptime() returned %p (%d)\n", ret, *ret);
return 0;
}
Here is the output:
$ gcc timetest.c ; ./a.out
6
strptime() returned 0x10c72af83 (0)
Here is the clang version I use:
$ clang -v
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin16.1.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
I think the reason is simply that, by design, the strptime function only sets the fields that appear in the format. Essentially, strptime(3) just parses fields from a given string using a supplied format into a referenced structure and performs no other computation or logic. Since your code uses the format %F %T then only the fields corresponding to %Y-%m-%d and %H:%M:%S (namely tm_{year,mon,mday,hour,min,sec}) are modified.
You can experiment by explicitly setting t.tm_wday to some known value that shouldn't by set by strptime (e.g. 123) and verify that it is not changed by that call. Note that you should probably initialize your struct tm before playing with it since any of those fields may contain random values, e.g. struct tm t; memset((void *) &t, 0, sizeof(t));.
Moreover, this Linux strptime(3) man page contains the following note which leads me to believe that the special behavior it describes is non-standard (though obviously desirable):
The glibc implementation does not touch those fields which are not explicitly specified, except that it recomputes the tm_wday and tm_yday field if any of the year, month, or day elements changed.
This answer shows how you can use the trio of strptime/mktime/localtime (or gmtime) to populate the tm.tm_wday field for dates after the UNIX epoch.
Following on from the observation in the comments, here's a program derived from your code which illustrates, even if it does not explain, what is going on:
#include <time.h>
#include <stdio.h>
static void dump_struct_tm(const char *tag, const struct tm *t)
{
printf("%s:\n", tag);
printf(" Time: %.2d:%.2d:%.2d ", t-> tm_hour, t->tm_min, t->tm_sec);
printf(" Date: %.4d-%.2d-%.2d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
printf(" Wday: %d Yday: %.3d (DST %d Zone [%s] offset %ld)\n",
t->tm_wday, t->tm_yday, t->tm_isdst, t->tm_zone, t-> tm_gmtoff);
}
int main(void)
{
time_t epoch = 0;
struct tm t;
char *ret;
t = *localtime(&epoch);
dump_struct_tm("Epoch", &t);
putchar('\n');
ret = strptime("2015-04-19 12:00:00", "%F %T", &t);
dump_struct_tm("strptime()", &t);
time_t rt = mktime(&t);
dump_struct_tm("mktime()", &t);
printf("Weekday: %d\n", t.tm_wday);
printf("strptime() returned %p (%d)\n", ret, *ret);
printf("Unix time: %lld\n\n", (long long)rt);
t.tm_isdst = -1;
ret = strptime("2015-04-19 12:00:00", "%F %T", &t);
dump_struct_tm("strptime()", &t);
rt = mktime(&t);
dump_struct_tm("mktime()", &t);
printf("Weekday: %d\n", t.tm_wday);
printf("strptime() returned %p (%d)\n", ret, *ret);
printf("Unix time: %lld\n\n", (long long)rt);
return 0;
}
This analyzes the struct tm (as defined by the manual page on macOS Sierra) at different points. Note how the setting of tm_isdst alters the behaviour.
Epoch:
Time: 16:00:00 Date: 1969-12-31
Wday: 3 Yday: 364 (DST 0 Zone [PST] offset -28800)
strptime():
Time: 12:00:00 Date: 2015-04-19
Wday: 6 Yday: 108 (DST 0 Zone [(null)] offset -28800)
mktime():
Time: 13:00:00 Date: 2015-04-19
Wday: 0 Yday: 108 (DST 1 Zone [PDT] offset -25200)
Weekday: 0
strptime() returned 0x100c82f0c (0)
Unix time: 1429473600
strptime():
Time: 12:00:00 Date: 2015-04-19
Wday: 6 Yday: 108 (DST -1 Zone [(null)] offset -25200)
mktime():
Time: 12:00:00 Date: 2015-04-19
Wday: 0 Yday: 108 (DST 1 Zone [PDT] offset -25200)
Weekday: 0
strptime() returned 0x100c82f0c (0)
Unix time: 1429470000
I'm still not clear why strptime() mispopulates the tm_wday field, especially since it seems to get the tm_yday field correct. The 19th of April is day 108 of the year when the 1st of January is day 0.

Convert current milliSecond to time format using C

i need to convet current time in milliseconds to human readable time format. I have following code
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/time.h>
#include <time.h>
int Cnvrt_To_Time_Frmt(char *Epochval)
{
unsigned long epoch = 0;
time_t tt = 0;
char timestamp[64],usec_buf[20];
if (!sscanf(Epochval, "%lu", &epoch))
{
return 1;
}
tt = epoch;
strftime(timestamp, 64, "%c", localtime(&tt));
printf("%s\n",timestamp);
return 0;
}
int main()
{
uint64_t Epoch_time=1468496250207;
char str_ms[256];
sprintf(str_ms, "%llu", (Epoch_time/1000));
Cnvrt_To_Time_Frmt(str_ms);
}
It produce result : Thu Jul 14 17:07:30 2016.
But i need to print result with milli seconds. like Thu Jul 14 17:07:30:40 2016.(17 hour,07 minute, 30 second, 40 milliSecond)
How it will be possible?
Type time_t by its definition doesn't represent time with milliseconds resolution, function localtime returns pointer to struct tm which does not include milliseconds, function strftime is not designed to produce strings with milliseconds.
If you need time with milliseconds you can use timeb stucture with its associated ftime function if those are supported by your tool-chain.
Use this as format string:
strftime(timestamp, 64, "%a %b %d %H:%M:%S.XXX %Y", localtime(&tt));
The XXX will be copied as-is into the time string.
Then in main, you can overwrite the Xs with the millisecond count.
sprintf(&timestamp[20], "%03u", (unsigned)Epoch_time%1000);
timestamp[23] = ' '; // restore the NUL to space again
After that, refactor your code so the divisions and remainder operations are done inside Cnvrt_To_Time_Frmt. You could use this as prototype:
int msecs_tostr(char *buffer, const char *msecs_since_epoch);
I don't have 50 reps yet so I can't comment so I will write my suggestion as an answer here.
You can use the other guys suggestions they are pretty good or you can make your own struct and a function that converts the mili seconds into time , by using basic math functions.
Make a struct that contains dayOfWeek , month , dayOfMonth , hour, minute, second , milliSecond , year.
Make a convertFunction that will receive a value of milliSeconds that need to be converted to your struct format.
Maybe its not the best way to do it , but if you don't find a way of using existing libraries , make your own .
... need to print result with milli seconds. ... How it will be possible?
Take it step by step
uint64_t Epoch_time=1468496250207;
// Break time into a whole number of seconds and ms fraction
time_t t_unix = Epoch_time/1000;
unsigned t_ms = Epoch_time%1000;
// Convert to YMD HMS structure
struct tm tm = *localtime(&t_unix);
// Form left portion of string
char left[64];
strftime(left, sizeof left, "%a %b %d %H:%M", &tm);
// Form right portion of string
char right[20];
strftime(right, sizeof right, "%Y", &tm);
// Put together with ms
char timestamp[64];
snprintf(timestamp, sizeof timestamp, "%s:%u %s", left, t_ms, right);
// Thu Jul 14 17:07:30:40 2016
// Print as needed
puts(timestamp);
Robust code would add error checking with each function's return value.
[edit]
Evidently OP's time stamp's last 3 digits are a fraction / 512.
unsigned t_fraction = Epoch_time%1000;
...
snprintf(timestamp, sizeof timestamp, "%s:%02u %s", left, t_fraction*100/512, right);
This example program will both retrieve the current timestamp from they system OS, and print it out in human readable format. It is similar to #user:2410359 answer, but a little more concise.
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
/*
* timestamp - read and print the current timestamp
* Wade Ryan 2020-09-27
* compile using: g++ timestamp.cpp -o timestamp
*/
int main(int argc, char **argv) {
char timestamp[24];
struct timeval currentTime;
struct tm ts;
gettimeofday(&currentTime, NULL);
long long epoch = (unsigned long long)(currentTime.tv_sec) * 1000 +
(unsigned long long)(currentTime.tv_usec) / 1000;
strftime(timestamp, sizeof(timestamp), "%F %T", localtime(&currentTime.tv_sec));
printf("epoch %lld ms :: %s.%03ld\n", epoch, timestamp, currentTime.tv_usec/1000);
}
Example output:
epoch 1601259041504 ms :: 2020-09-27 21:10:41.504

strftime issues day of the week

char buffer[800];
struct tm str_time;
str_time.tm_mday = Cur_Day;
str_time.tm_mon = Cur_Month - 1;
str_time.tm_year = entries[i].Year_Start - 1900;
int len = strftime(buffer, 100, "%A, %d %B %Y", &str_time);
printf("\n%s\n", buffer);
What about the above results in the day of the week always being Sunday, regardless of values of Cur_Day and Cur_Month?
Sample output:
Sunday, 23 November 2012
------------------------
stuff
Sunday, 25 November 2012
------------------------
stuff
Sunday, 26 November 2012
------------------------
stuff
Your str_time structure (if, as it seems to be, it's a local variable) has indeterminate values in its fields unless you explicitly set them. All strftime does is use the values it has, it doesn't first adjust values to conform other fields.
Since you're not setting tm_wday, it will stay with whatever it was originally (0 by the looks of it, since it's always Sunday).
If you do want to adjust fields based on other fields, you should look into mktime().
From the standard (ISO C99):
The mktime function converts the broken-down time, expressed as local time, in the
structure pointed to by timeptr into a calendar time value with the same encoding as
that of the values returned by the time function.
The original values of the tm_wday and tm_yday components of the structure are ignored, and the original values of the other components are not restricted to the ranges indicated above.
On successful completion, the values of the tm_wday and tm_yday components of the structure are set appropriately, and the other components are set to represent the specified calendar time, but with their values forced to the ranges indicated above; the final value of tm_mday is not set until tm_mon and tm_year are determined.
Your best bet is to use time() and localtime() to populate a tm structure, then change the fields you want to change before calling mktime(). That way, you're guaranteed that all fields will have sensible values.
The following program shows one way to do this:
#include <stdio.h>
#include <time.h>
int main (void) {
char buffer[100];
time_t now;
struct tm *ts;
// Get today in local time and output it.
now = time (NULL);
struct tm *ts = localtime (&now);
strftime (buffer, 100, "%A, %d %B %Y", ts);
printf ("Now = %s\n", buffer);
// Advance day-of-month and make new date.
// Probably need to intelligently handle month rollover.
ts->tm_mday++;
mktime (ts);
strftime (buffer, 100, "%A, %d %B %Y", ts);
printf ("Tomorrow = %s\n", buffer);
return 0;
}
The output of that program is:
Now = Tuesday, 09 October 2012
Tomorrow = Wednesday, 10 October 2012
For what it's worth, here's a complete program that uses that method to give you the day of the week for a given date (defaults to today).
You can change the year, month and day of month with the optional -y, -m and -d arguments in any order you want, and as many times as you want, though only the last for each type counts.
#include <stdio.h>
#include <time.h>
static int makeError (char *argVal, char *errStr) {
printf ("Error with argument '%s': %s\n", argVal, errStr);
printf ("Usage: dow [-y<year>] [-m<month>] [-d<day>]\n");
return 1;
}
int main (int argc, char *argv[]) {
int idx, intVal;
char chVal;
char buff[100];
time_t now = time (NULL);
struct tm *nowStr = localtime (&now);
for (idx = 1; idx < argc; idx++) {
chVal = (*argv[idx] != '-') ? '\0' : *(argv[idx] + 1);
if ((chVal != 'y') && (chVal != 'm') && (chVal != 'd'))
return makeError (argv[idx], "does not start with '-y/m/d'");
intVal = atoi (argv[idx] + 2);
if (intVal < 0)
return makeError (argv[idx], "suffix is negative");
sprintf (buff, "%d", intVal);
if (strcmp (buff, argv[idx] + 2) != 0)
return makeError (argv[idx], "suffix is not numeric");
switch (chVal) {
case 'y': nowStr->tm_year = intVal - 1900; break;
case 'm': nowStr->tm_mon = intVal - 1; break;
case 'd': nowStr->tm_mday = intVal; break;
}
}
mktime (nowStr);
strftime (buff, sizeof (buff), "%A, %d %B %Y", nowStr);
printf ("%s\n", buff);
return 0;
}
A sample transcript:
pax> ./dow
Tuesday, 09 October 2012
pax> ./dow -y2011
Sunday, 09 October 2011
pax> ./dow -y2000 -m1 -d1
Saturday, 01 January 2000
The most probable explanation is that your strftime requires tm_wday to have a meaningful value if you're going to ask it to print the day of the week.
This is the simplest available way to avoid having to compute it yourself:
struct tm tm;
memset(&tm, 0, sizeof(struct tm));
tm.tm_mday = Cur_Day;
tm.tm_mon = Cur_Month - 1;
tm.tm_year = entries[i].Year_Start - 1900;
tm.tm_hour = 12;
(void) timegm(&tm); /* fills in the rest of `tm` as a side effect */
/* now call strftime */
If you don't have timegm you MAY be able to get away with using mktime instead (the problems with doing this calculation in 'local' time are largely irrelevant if you only want to print the date). DO NOT use the "portable version of timegm" described in the Linux manpage for timegm, it has portability gotchas waiting to bite on almost every line!
You need to set str_time.tm_wday so that strftime() can convert it.
See localtime(3) and strftime(3) for examples.

C extract some data from my string with sscanf or else

I am very poor in C, I just learning it. I have a string like:
a 322 4.1 5.2
(with whitespaces/tabs/spaces)
or
b 1.22 4.1 5.2 4.11
what is the way to get all the strings without whitespace
so:
string[0]="s";
string[1]="322";
string[2]="4.1";
etc...
edit
I just trying to find the best/fastest way to do it, for big line numbers. (70-100.000 strings)
Working on Android/galaxy s/linkedlist
test: 71.000 arrays took about 7-8 seconds with C++(without string/std), 14 sec with java
What the original poster asked using sscanf():
#include <stdio.h>
#include <string.h>
int main(){
// 5 elements, each of 32 bytes, 31 for characters the 32nd for storing \0
char string[5][32];
char* inputString="a 322 4.1 5.2";
memset(string,0,sizeof(string));//to initialize to NULL, always be safe on C
sscanf(inputString,"%s%s%s%s",string[0],string[1],string[2],string[3]);
printf("res0= %s\n",string[0]);
printf("res1= %s\n",string[1]);
printf("res2= %s\n",string[2]);
printf("res2= %s\n",string[3]);
return 0;
}
This will print:
res0= a
res1= 322
res2= 4.1
res2= 5.2
You can use strtok, as Martin Beckett said, which is recommended for portability. However, if your system has strsep available, I'd go with it. Its man page on BSD has the solution to your question in the examples section.
#include <string.h>
int main()
{
char input[] = " a 322 4.1 5.2";
char **ap, *argv[5], *inputstring = input;
for (ap = argv; (*ap = strsep(&inputstring, " \t")) != NULL;)
if (**ap != '\0')
if (++ap >= &argv[10])
break;
/* degubber output for `p argv':
*
* $1 = {
* 0x1001009a1 "a",
* 0x1001009ac "322",
* 0x1001009b1 "4.1",
* 0x1001009b7 "5.2",
* 0x0
* }
*/
}
Safest way to split a string (especially if you don't know what the string may contain) is strtok.
You might also need to check how you are creating the string[] array in 'C'
for(int i=0,j=0; str[i]; i++)
{
if(str[i]==' ')
continue;
str2[j]=str[i];
j++;
}
In the above code, str is your previous string and str1 is the new.

How to get the date and time values in a C program?

I have something like this:
char *current_day, *current_time;
system("date +%F");
system("date +%T");
It prints the current day and time in the stdout, but I want to get this output or assign them to the current_day and current_time variables, so that I can do some processing with those values later on.
current_day ==> current day
current_time ==> current time
The only solution that I can think of now is to direct the output to some file, and then read the file and then assign the values of date and time to current_day and current_time. But I think this is not a good way. Is there any other short and elegant way?
Use time() and localtime() to get the time:
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("now: %d-%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);
}
strftime (C89)
Martin mentioned it, here's an example:
main.c
#include <assert.h>
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char s[64];
size_t ret = strftime(s, sizeof(s), "%c", tm);
assert(ret);
printf("%s\n", s);
return 0;
}
GitHub upstream.
Compile and run:
gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out
Sample output:
Thu Apr 14 22:39:03 2016
The %c specifier produces the same format as ctime.
One advantage of this function is that it returns the number of bytes written, allowing for better error control in case the generated string is too long:
RETURN VALUE
Provided that the result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the terminating null byte) placed in the array s. If the length of the result string (including the terminating null byte) would exceed max bytes, then strftime() returns 0, and the contents of the array are undefined.
Note that the return value 0 does not necessarily indicate an error. For example, in many locales %p yields an empty string. An empty format string will likewise yield an empty string.
asctime and ctime (C89, deprecated in POSIX 7)
asctime is a convenient way to format a struct tm:
main.c
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("%s", asctime(tm));
return 0;
}
Sample output:
Wed Jun 10 16:10:32 2015
And there is also ctime() which the standard says is a shortcut for:
asctime(localtime())
As mentioned by Jonathan Leffler, the format has the shortcoming of not having timezone information.
POSIX 7 marked those functions as "obsolescent" so they could be removed in future versions:
The standard developers decided to mark the asctime() and asctime_r() functions obsolescent even though asctime() is in the ISO C standard due to the possibility of buffer overflow. The ISO C standard also provides the strftime() function which can be used to avoid these problems.
C++ version of this question: How to get current time and date in C++?
Tested in Ubuntu 16.04.
time_t rawtime;
time ( &rawtime );
struct tm *timeinfo = localtime ( &rawtime );
You can also use strftime to format the time into a string.
To expand on the answer by Ori Osherov
You can use the WinAPI to get the date and time, this method is specific to Windows, but if you are targeting Windows only, or are already using the WinAPI then this is definitly a possibility1:
You can get both the time and date by using the SYSTEMTIME struct. You also need to call one of two functions (either GetLocalTime() or GetSystemTime()) to fill out the struct.
GetLocalTime() will give you the time and date specific to your time zone.
GetSystemTime() will give you the time and date in UTC.
The SYSTEMTIME struct has the following members:
wYear, wMonth, wDayOfWeek, wDay, wHour, wMinute, wSecond and wMilliseconds
You then need to just access the struct in the regular way
Actual example code:
#include <windows.h> // use to define SYSTEMTIME , GetLocalTime() and GetSystemTime()
#include <stdio.h> // For printf() (could otherwise use WinAPI equivalent)
int main(void) { // Or any other WinAPI entry point (e.g. WinMain/wmain)
SYSTEMTIME t; // Declare SYSTEMTIME struct
GetLocalTime(&t); // Fill out the struct so that it can be used
// Use GetSystemTime(&t) to get UTC time
printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute:%d, Second: %d, Millisecond: %d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); // Return year, month, day, hour, minute, second and millisecond in that order
return 0;
}
(Coded for simplicity and clarity, see the original answer for a better formatted method)
The output will be something like this:
Year: 2018, Month: 11, Day: 24, Hour: 12, Minute:28, Second: 1, Millisecond: 572
Useful References:
All the WinAPI documentation (most already listed above):
GetLocalTime()
GetSystemTime()
SYSTEMTIME
Time Functions
An extremely good beginners tutorial on this subject by ZetCode:
https://zetcode.com/gui/winapi/datetime/
Simple operations with datetime on Codeproject:
https://www.codeproject.com/Articles/5546/WinAPI-Simple-Operations-with-datetime
1: As mentioned in the comments in Ori Osherov's answer ("Given that OP started with date +%F, they're almost certainly not using Windows. – melpomene Sep 9 at 22:17") the OP is not using Windows, however since this question has no platform specific tag (nor does it mention anywhere that the answer should be for that particular system), and is one of the top results when Googling "get time in c" both answers belong here, some users searching for an answer to this question may be on Windows and therefore will be useful to them.
Timespec has day of year built in.
http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html
#include <time.h>
int get_day_of_year(){
time_t t = time(NULL);
struct tm tm = *localtime(&t);
return tm.tm_yday;
}`
The answers given above are good CRT answers, but if you want you can also use the Win32 solution to this. It's almost identical but IMO if you're programming for Windows you might as well just use its API (although I don't know if you are programming in Windows).
char* arrDayNames[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
SYSTEMTIME st;
GetLocalTime(&st); // Alternatively use GetSystemTime for the UTC version of the time
printf("The current date and time are: %d/%d/%d %d:%d:%d:%d", st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
printf("The day is: %s", arrDayNames[st.wDayOfWeek]);
Anyway, this is a Windows solution. I hope it will be helpful for you sometime!
I was using command line C-compiler to compile these and it completely drove me bonkers as it refused to compile.
For some reason my compiler hated that I was declaring and using the function all in one line.
struct tm tm = *localtime(&t);
test.c
test.c(494) : error C2143: syntax error : missing ';' before 'type'
Compiler Status: 512
First declare your variable and then call the function. This is how I did it.
char todayDateStr[100];
time_t rawtime;
struct tm *timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
strftime(todayDateStr, strlen("DD-MMM-YYYY HH:MM")+1,"%d-%b-%Y %H:%M",timeinfo);
printf("todayDateStr = %s ... \n", todayDateStr );
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct date
{
int month;
int day;
int year;
};
int calcN(struct date d)
{
int N;
int f(struct date d);
int g(int m);
N = 1461 * f(d) / 4 + 153 * g(d.month) / 5 + d.day;
if(d.year < 1700 || (d.year == 1700 && d.month < 3))
{
printf("Date must be after February 29th, 1700\n");
return 0;
}
else if(d.year < 1800 || (d.year == 1800 && d.month < 3))
N += 2;
else if(d.year < 1900 || (d.year == 1900 && d.month < 3))
N += 1;
return N;
}
int f(struct date d)
{
if(d.month <= 2)
d.year -= 1;
return d.year;
}
int g(int m)
{
if(m <=2)
m += 13;
else
m += 1;
return m;
}
int main(void)
{
int calcN(struct date d);
struct date d1, d2;
int N1, N2;
time_t t;
time(&t);
struct tm *now = localtime(&t);
d1.month = now->tm_mon + 1;
d1.day = now->tm_mday;
d1.year = now->tm_year + 1900;
printf("Today's date: %02i/%02i/%i\n", d1.month, d1.day, d1.year);
N1 = calcN(d1);
printf("Enter birthday (mm dd yyyy): ");
scanf("%i%i%i", &d2.month, &d2.day, &d2.year);
N2 = calcN(d2);
if(N2 == 0)
return 0;
printf("Number of days since birthday: %i\n", N1 - N2);
return 0;
}
#include <stdio.h>
int main() {
char *pts; /* pointer to time string */
time_t now; /* current time */
char *ctime();
(void) time(&now);
printf("%s", ctime(&now));
return(0);
}
Sample output:
Sat May 14 19:24:54 2022
This is the easiest way. I haven't even used time.h.
Be advised: The output produced has a newline at the end.
instead of files use pipes and if u wana use C and not C++ u can use popen like this
#include<stdlib.h>
#include<stdio.h>
FILE *fp= popen("date +F","r");
and use *fp as a normal file pointer with fgets and all
if u wana use c++ strings, fork a child, invoke the command and then pipe it to the parent.
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
string currentday;
int dependPipe[2];
pipe(dependPipe);// make the pipe
if(fork()){//parent
dup2(dependPipe[0],0);//convert parent's std input to pipe's output
close(dependPipe[1]);
getline(cin,currentday);
} else {//child
dup2(dependPipe[1],1);//convert child's std output to pipe's input
close(dependPipe[0]);
system("date +%F");
}
// make a similar 1 for date +T but really i recommend u stick with stuff in time.h GL
#include<stdio.h>
using namespace std;
int main()
{
printf("%s",__DATE__);
printf("%s",__TIME__);
return 0;
}

Resources