Menu

How to get real time and date?

2002-08-11
2012-09-26
  • Nobody/Anonymous

    How do you get the time and date in c++ Console programs?, I know its in Time.h somewhere...but where?

     
    • Nobody/Anonymous

      Try this for getting local time from your PC, might have a bit more than what you want but it works OK with the Dev compiler

      #include <time.h>
      #include <stdio.h>
      #include <conio.c>
      #include <conio.h>
      #include <iostream.h>
      #include <fstream.h>
      #include <string>
      void read();

      int main(int argc, char *argv[])
      {
      textcolor(LIGHTGREEN);
      string hr,min,sec,mon;
      time_t t;

      struct tm *now;

      time(&t);
      now = localtime(&t);

      if(now->tm_mon<10){
      mon="0";
      }else{
      mon="";
      }
      if(now->tm_hour<10){
      hr="0";
      }else{
      hr="";
      }
      if(now->tm_min<10){
      min="0";
      }else{
      min="";
      }
      if(now->tm_sec<10){
      sec="0";
      }else{
      sec="";
      }

      //Print the date and time to the screen
      cout<<"The date is "<<now->tm_mday + 1<<":"<<mon<<now->tm_mon + 1<<":"<<now->tm_year + 1900<<"\n The time is "<<hr<<now->tm_hour<<":"<<min<<now->tm_min<<" and "<<sec<<now->tm_sec<<" seconds \n According to your computors clock";
      //set up fstream to write to a txt file with the handle trev

      ofstream trev("c:\\time.txt",ios::ate);
      cout<<" \n\n\nPress Enter to carry on\n";
      getche();
      clrscr();
      //write to the file
      trev<<"You accessed this programme on "<<now->tm_mday + 1<<":"<<mon<<now->tm_mon + 1<<":"<<now->tm_year + 1900<<"\n at "<<hr<<now->tm_hour<<":"<<min<<now->tm_min<<" and "<<sec<<now->tm_sec<<" seconds"<<endl;

      //tell them you have written to the screen
      cout<<" \n\nI have just written to a file on your C drive called time.txt\n";
      //carry on to read the file
      cout<<"\n\nPress Enter to view file\n";
      getche();
      clrscr();
      read();
      return 0;
      }

      void read() //the bit that reads the file

      {

      ifstream OpenFile("c:\\time.txt");

      char ch;

      while(!OpenFile.eof())

      {

      OpenFile.get(ch);

      cout << ch;

      }

      OpenFile.close();
      getche();

      }

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.