How to get current time in C using gettime()? - c

We're required to use gettime() to get the current time in C. I'm trying to print the current time but the error:
error: storage size of 't' isn't known
occurs. I don't know how to solve this. Here is the code:
#include<stdio.h>
#include<dos.h>
int main(){
struct time t;
gettime(&t);
printf("%d:%d:%d", t.ti_hour,t.ti_min,t.ti_sec);
getch();
return 0;
}

It's not clear if you want to get the time, or just print it.
For the second case, there are few legacy methods that will provide formatted time (asctime, ctime). But those may not fit your needs.
The more flexible option is to use strftime based on data from time/localtime_r. The strftime support many of the escapes (%Y, ...) that are available with GNU date.
#include <stdio.h>
#include <time.h>
void main(void)
{
time_t now = time(NULL) ;
struct tm tm_now ;
localtime_r(&now, &tm_now) ;
char buff[100] ;
strftime(buff, sizeof(buff), "%Y-%m-%d, time is %H:%M", &tm_now) ;
printf("Time is '%s'\n", buff) ;
}

The standard C function to get the local time is simply time, included in the header time.h
Example taken from here.
/* time example */
#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, difftime, time, mktime */
int main ()
{
time_t timer;
struct tm y2k = {0};
double seconds;
y2k.tm_hour = 0; y2k.tm_min = 0; y2k.tm_sec = 0;
y2k.tm_year = 100; y2k.tm_mon = 0; y2k.tm_mday = 1;
time(&timer); /* get current time; same as: timer = time(NULL) */
seconds = difftime(timer,mktime(&y2k));
printf ("%.f seconds since January 1, 2000 in the current timezone", seconds);
return 0;
}
More info on the different time format :
http://www.cplusplus.com/reference/ctime/mktime/
http://www.cplusplus.com/reference/ctime/localtime/

Ok, you're trying to use the DOS.H library, so the time.h and ctime library does not apply to this particular issue due to DOS.H is an exclusive C library you cannot use it in any other C (C++ or C#), please read the library after you read this post so you can see clearly what am i talking about, so within the DOS.H library is an STRUCT that you use for save all the variables of time, this is hour, minutes, seconds, so the first thing that we have to do is to declare a variable that allow us save this type of data:
struct time tm;
Once you do that you can use the gettime() function wich is on the library to, this to save que values in a place where we can get access to:
gettime(&tm);
And finally to print o do wherever you want with this data you need to get each register of the structure:
printf("System time is: %d : %d : %d\n",tm.ti_hour, tm.ti_min, tm.ti_sec);
Check this code:
#include<stdio.h>
#include<dos.h>
#include<conio.h>
int main()
{
struct date fecha;
struct time hora;
union REGS regs;
getdate(&fecha);
printf("La fecha del sistema es: %d / %d / %d\n",fecha.da_day,fecha.da_mon,fecha.da_year);
regs.x.cx = 0x004c;
regs.x.dx = 0x4b40;
regs.h.ah = 0x86; /* 004c4b40h = 5000000 microsegundos */
int86(0x15,&regs,&regs); /* Interrupcion 15h suspension de sistema */
gettime(&hora);
printf("la hora del sistema es: %d : %d : %d\n",hora.ti_hour,hora.ti_min,hora.ti_sec);
getche();
clrscr();
return 0;
}

Related

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

Time isnt correct but code seems to be correct :S (unexpected outcome)

So im trying to build a program that tells u the exact time in years, days, hours and mins.
i have checked my code over and it seems to be okay and the outcomes are close to correct but aren't exactly correct, i have posted my code below:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void year_day(time_t seconds, float *yearsLPtr, float *dayLPtr){
int yearS;
float t_constant;//seconds per year
t_constant = 365.2425*24*60*60; //seconds in a year (years to 4dp)
*yearsLPtr =(seconds/t_constant);// years as float since 1970 1/1 00:00
yearS=*yearsLPtr; //sending float to int
*dayLPtr = (((seconds/t_constant) - yearS)*365.2425);//used exact number for years to neglext error
*yearsLPtr+=1970; //adding 1970 to change in years to get current year
}
void hours_minutes(float dayL, float *hoursLPtr, float *minsLPtr){
float t_constant;
int dayS, minS;
dayS=dayL;
t_constant= 365.2425*24*60*60;
*hoursLPtr= (dayL-dayS)*24;
minS= *hoursLPtr;
*minsLPtr= (((dayL-dayS)*24)-minS)*60;
}
void print_time (float yearsL, float dayL, float hoursL, float minsL){
int constant, yearsS, dayS, hoursS, minsS;
yearsS=yearsL; //converting from float back to int, couldve pointed to int straight away tho
dayS=dayL;
hoursS=hoursL;
minsS=minsL;
printf("Year: %i \t", yearsS);
printf("Day: %i \t",dayS);
printf("Hour: %i \t",hoursS);
printf("Min: %i \t",minsS);
}
int main() {
float yearsL, dayL, hoursL, minsL;
time_t current_seconds; //time t like long/double for longer values
current_seconds=time(NULL);
year_day(current_seconds,&yearsL,&dayL);
hours_minutes(dayL,&hoursL,&minsL);
print_time(yearsL,dayL,hoursL,minsL);
getchar();
}
one problem that I see is that you have used only time(). this function does not return time for your time zone. if you need time for your time zone, you need to use localtime() to get correct time.
You should use the libraries that are available to you:
http://www.tutorialspoint.com/c_standard_library/time_h.htm
http://www.codingunit.com/c-tutorial-how-to-use-time-and-date-in-c
from the tutorial linked above:
time_t now;
now = time(NULL); // read the time into 'now'
printf(ctime(&now)); // prints all of the information you are looking for and then some
If you don't like the way that time is formatted, use the functions localTime() and strftime():
#define DEFAULT_STR_LEN 80
char strNow[DEFAULT_STR_LEN] = {0};
time_t = rawTime;
struct tm *localTime;
time(&rawTime);
localTime = localtime(&rawTime);
strftime(str, DEFAULT_STR_LEN, "%H:%M:%S", localTime);
printf(str);
There are lots of % arguments for the strftime() function, take a look around.

How to add milliseconds in printing the current system time as a timestamp in C? [duplicate]

I want to print time in the format hh:mm:ss:ms(milliseconds). I could print in the form of hh:mm:ss. What can be the way to print remaining milliseconds?
#include<sys/timeb.h>
#include<time.h>
int main(void) {
struct timeb tp;
ftime(&tp);
char timeString[80];
strftime(timeString, sizeof(timeString), "%H:%M:%S", localtime(&tp.time));
printf("%s:%d", timeString, tp.millitm);
return 0;
}
This is what I use in linux ...
struct timeval tv;
gettimeofday(&tv,0);
time_t long_time;
struct tm *newtime;
time(&long_time);
newtime = localtime(&long_time);
char result[100] = {0};
sprintf(result, "%02d:%02d:%02d.%03ld", newtime->tm_hour,newtime->tm_min,newtime->tm_sec, (long)tv.tv_usec / 1000);
return result;
I have no experience working in windows .. try to find similar calls ..
If you're working with the MSDN library, you could try
GetSystemTimeAsFileTime( pointerToSetToTime );
Which sets a pointer argument to the current system time in 100-nanosecond intervals.

Calculating elapsed time in a C program in milliseconds

I want to calculate the time in milliseconds taken by the execution of some part of my program. I've been looking online, but there's not much info on this topic. Any of you know how to do this?
Best way to answer is with an example:
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
/* Return 1 if the difference is negative, otherwise 0. */
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1)
{
long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);
result->tv_sec = diff / 1000000;
result->tv_usec = diff % 1000000;
return (diff<0);
}
void timeval_print(struct timeval *tv)
{
char buffer[30];
time_t curtime;
printf("%ld.%06ld", tv->tv_sec, tv->tv_usec);
curtime = tv->tv_sec;
strftime(buffer, 30, "%m-%d-%Y %T", localtime(&curtime));
printf(" = %s.%06ld\n", buffer, tv->tv_usec);
}
int main()
{
struct timeval tvBegin, tvEnd, tvDiff;
// begin
gettimeofday(&tvBegin, NULL);
timeval_print(&tvBegin);
// lengthy operation
int i,j;
for(i=0;i<999999L;++i) {
j=sqrt(i);
}
//end
gettimeofday(&tvEnd, NULL);
timeval_print(&tvEnd);
// diff
timeval_subtract(&tvDiff, &tvEnd, &tvBegin);
printf("%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec);
return 0;
}
Another option ( at least on some UNIX ) is clock_gettime and related functions. These allow access to various realtime clocks and you can select one of the higher resolution ones and throw away the resolution you don't need.
The gettimeofday function returns the time with microsecond precision (if the platform can support that, of course):
The gettimeofday() function shall
obtain the current time, expressed as
seconds and microseconds since the
Epoch, and store it in the timeval
structure pointed to by tp. The
resolution of the system clock is
unspecified.
C libraries have a function to let you get the system time. You can calculate elapsed time after you capture the start and stop times.
The function is called gettimeofday() and you can look at the man page to find out what to include and how to use it.
On Windows, you can just do this:
DWORD dwTickCount = GetTickCount();
// Perform some things.
printf("Code took: %dms\n", GetTickCount() - dwTickCount);
Not the most general/elegant solution, but nice and quick when you need it.

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