Hi all,
How do i get the system time in C++?
thnks!
Printable View
Hi all,
How do i get the system time in C++?
thnks!
Code:# define TIME_SIZE 40
const struct tm *tm;
size_t len;
time_t now;
char *s;
now = time ( NULL );
tm = localtime ( &now );
s = new char[TIME_SIZE];
len = strftime ( s, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm );
You can make use of strftime.
You can make use of _strtime but it's non-portable and may not work on every system.Code:#include <iostream>
#include <ctime>
#include <cerrno>
int main()
{
//Find the current time
time_t curtime = time(0);
//convert it to tm
tm now=*localtime(&curtime);
//BUFSIZ is standard macro that expands to a integer constant expression
//that is greater then or equal to 256. It is the size of the stream buffer
//used by setbuf()
char dest[BUFSIZ]={0};
//Format string determines the conversion specification's behaviour
const char format[]="%A, %B %d %Y. The time is %X";
//strftime - converts date and time to a string
if (strftime(dest, sizeof(dest)-1, format, &now)>0)
std::cout<<dest<<std::endl;
else
std::cerr<<"strftime failed. Errno code: "<<errno<<std::endl;
}
Code:#include <iostream>
#include <ctime>
int main ()
{
char time [10];
_strtime(time);
std::cout<<"Current Time:"<<time;
return 0;
}
On windows Using Win32 API we can make it very simple.
You can find details for all other related functions hereCode:#include<iostream>
#include<windows.h>
int main(){
SYSTEMTIME st;
GetLocalTime(&st);
std::cout<<st.wHour<<":"<<st.wMinute<<":"<< st.wSecond;
return 0;
}
You can use GetSystemTime. Here is the list of all Windows time functions.