Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ MFC Get current date and time

Tags:

c++

date

time

mfc

I've been programming in VB.NET for most of my very programming career. I have a C++ project provided to me, which I need to make a few modifications, and I am feeling hopelessly lost and confused.

It is a Visual Studio 2008 MFC project in C++.

an output variable has been defined:

char szout[900];

This line below, is used to append values to the output variable before output:

strcpy(szout, "TextHere")

So one of the many examples from searching, that i have tried, was to include at the top:

#include <windows.h>

And then for my code:

SYSTEMTIME st;
GetSystemTime(&st);
char myDate[20] = st;
CT2CA outputDate(myDate);
strcat(szout, outputDate);

For some reason the variables appended on to szout must be of type CT2CA, which i'm not really sure what this is either.

But then I get the following errors on the second and third line (char myDate...etc...) and (CT2CA output....etc....)

error C2440: 'initializing' : cannot convert from 'SYSTEMTIME' to 'char [20]'

error C2664: 'ATL::CW2AEX<>::CW2AEX(LPCWSTR) throw(...)' : cannot convert parameter 1 from 'char [20]' to 'LPCWSTR'

So I'll clarify, I am a complete novice with this, and would appreciate any and all help.

Thank you,

like image 512
Adam Avatar asked Aug 02 '11 19:08

Adam


People also ask

How do I get current date and time on MFC?

SYSTEMTIME st; GetSystemTime(&st); char myDate[20] = st; CT2CA outputDate(myDate); strcat(szout, outputDate);

How do I get the current date in Visual Studio?

To access the current system date as a String , use the DateString property. To get or set the current system time, use the TimeOfDay property.

How do you represent a date in C++?

To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program. There are four time-related types: clock_t, time_t, size_t, and tm. The types - clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer.


2 Answers

In MFC the following code is for current date in MMDDYYYY format.

CTime t = CTime::GetCurrentTime();
CString s = t.Format("%m%d%Y");
like image 54
Pabitra Dash Avatar answered Oct 07 '22 13:10

Pabitra Dash


If you are using MFC, why not:

// uses printf() format specifications for time
CString t = CTime::GetCurrentTime().Format("%H:%M");

// Or, if you have OLE Support
CString t = COleDateTime::GetCurrentTime().Format("%H:%M");
like image 42
Chad Avatar answered Oct 07 '22 14:10

Chad