views:

198

answers:

4

I am trying to get system date in a C program on a MSVC++ 6.0 compiler. I am using a system call:

system("date /T") (output is e.g. 13-Oct-08 which is date on my system in the format i have set)

but this prints the date to the i/o console.

How do i make take this date as returned by above system call and store it as a string value to a string defined in my code? Or

Is there any other API i can use to get the date in above mentioned format (13-Oct-08, or 13-10-08) ?

-AD

A: 

There are a couple of ways to do this using API functions, two that jump to mind are strftime and GetDateFormat.

I'd like to provide examples but I'm afraid I don't have a Win32 compiler handy at the moment. Hopefully the examples in the above documentation are sufficient.

Greg Hewgill
+1  A: 
#include <windows.h>
#include <iostream>

int main() {

  SYSTEMTIME systmDateTime = {};
  ::GetLocalTime(&systmDateTime);

  wchar_t wszDate[64] = {};
  int const result = ::GetDateFormatW(
    LOCALE_USER_DEFAULT, DATE_SHORTDATE,
    &systmDateTime, 0, wszDate, _countof(wszDate));

  if (result) {
    std::wcout << wszDate;
  }
}
Constantin
A: 

Have a read of Win32 Time functions; GetLocalTime may be your friend. There are also the standard C time functions, time and strftime.

For future reference, in a C program, it is almost always the wrong answer to invoke an external utility and capture it's STDOUT.

Adam Wright
A: 

Thanks for the pointers.

I used this and it served my purpose:

#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/timeb.h>
#include <string.h>
    int main()

    {  

        char tmpbuf[128];

        time_t ltime;

        struct tm *today;

        _strdate( tmpbuf );
        printf("\n before formatting date is %s",tmpbuf);  

        time(&ltime);
        today = localtime( &ltime );

        strftime(tmpbuf,128,"%d-%m-%y",today);
        printf( "\nafter formatting date is %s\n", tmpbuf );

    }

-AD

goldenmean