Get Current Time in mm/dd/yyyy in C++ - c++

I am using the following code for setting the time in a Date Control in MFC using C++
CTime date;
date = date.GetCurrentTime();
this->m_headerDate.SetTime(&date);
This will get the Date and set it to the control in what ever format the user machine uses. But I want to set it to a format of ONLY mm/dd/yyyy.
There should be some way of doing this in MFC. Are there any utility functions for this?
Thanks,

Without MFC:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
const int MAXLEN = 80;
char s[MAXLEN];
time_t t = time(0);
strftime(s, MAXLEN, "%m/%d/%Y", localtime(&t));
std::cout << s << '\n';
}
Compiled Code
With MFC:
This function formats a date as a date string for a specified locale. The function formats either a specified date or the local system date.
int GetDateFormat(
LCID Locale,
DWORD dwFlags,
CONST SYSTEMTIME* lpDate,
LPCTSTR lpFormat,
LPTSTR lpDateStr,
int cchDate
);
change LPCTSTR lpFormat to MM:dd:yyyy

If you're talking about getting a specific textual representation of a date/time, you can use strftime() to format a date in many different ways, including the one specified in your question.
You will need a variable of type time_t using the facilities in the ctime header. So you can either switch to using those times, or I believe CTime::GetTime( ) will give you one.
However, if you're talking about forcing a control to display it's date/time in a specific format, that's a property of the control itself. For example, CDateTimeCtrl provides a SetFormat() method which will modify how it displays its data.

Here I'm storing value in a CString variable
Try this code:
CString strTime;
CTime date;
date = GetCurrentTime();
strTime = date.Format(_T("%m/%d/%Y"));

I have found a way of doing this...not sure if this is the simplest way though
Since we already have a datetime control .All we can do is just use the Setformat Function of the DatetimeControl. PFB an example of this
CDateTimeCtrl m_DateTimeCtrl;
m_DateTimeCtrl.SetFormat(_T("MM/dd/yyyy"));
The above will set it up to the format of 01/14/2015 which is desired. Thanks to Paxdiablo, Himanshu and Irrational Person for the inputs. They did point me in right direction with different options.

Related

C++ winapi: How to transform current time into a string?

I want to convert the current time into a string to later display it using the Drawtext function in WM_PAINT. Format hh:mm:ss.
And what is the most convenient way of getting the time to later turn it into a string.
There are many ways to format a time string.
If you want a specific format you can format the string yourself:
WCHAR buf[100];
SYSTEMTIME st;
GetLocalTime(&st); // Local time
wsprintfW(buf, L"%.2u:%.2u:%.2u", st.wHour, st.wMinute, st.wSecond); // 24h format
DrawTextW(hDC, buf, -1, &yourRect, DT_LEFT);
If you want to format the time using the users preferences then you must call GetTimeFormat instead. Or you could use the C standard library functions.
When you get a WM_PAINT message you call BeginPaint and GetClientRect, then DrawText and finally EndPaint.

How to get timezone abbreviation under Windows

We are trying to get the timezone from std::tm with strftime:
char timezone[50];
strftime(timezone, sizeof(timezone), "%Z", &timeCreated);
On iOS, we get "EST" which is what we want. But on Windows, we get "Eastern Summer Time". Anybody know how to consistently get the current timezone in C++ in abbreviation form?
I consider making the abbreviation from the full name of the timezone by simply picking out the first character in each word. But I check the list of abbreviations and notice that we could have timezone like this one "Chuuk Time" and abbreviated as "CHUT". Which makes manually adjusting not possible.
Not the same as Question: Windows Timezone and their abbreviations? I don't need a full list of all timezones and abbreviations. But instead, I need a systematic way to the current timezone using for example strftime. I want them to use the system's current timezone and the the current local.
Using this free, open-source library that has been ported to VS-2013 and later:
#include "tz.h"
#include <iostream>
int
main()
{
using namespace std::chrono;
using namespace date;
std::cout << format("%Z\n", make_zoned(current_zone(), system_clock::now()));
}
This just output for me:
EDT
Fully documented.
This library uses the IANA timezone database, and when current_zone() is called, translates the current Windows timezone into the appropriate IANA timezone.
Time zone information under Windows is kept in registry, you can find it in the following registry key:
HKEY_LOCAL_MACHINE
SOFTWARE
Microsoft
Windows NT
CurrentVersion
Time Zones
time_zone_name
you will not find there any abbreviations. The reason is mostly because it is not standardised, and also one abbreviation can be assigned to many time zone names, for more read here. Your aproach with taking first letter is fine, you can look up names also on this wiki:
https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations
Also see this thread from MSDN forums:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/3aa4420a-a5bf-48a3-af13-17a0905ce366/is-there-any-way-to-get-timezone-abbreviations?forum=csharpgeneral
GetDynamicTimeZoneInformation is probably a good choice. However, the minimum supported versions are Windows Vista, Windows Server 2008 and Windows Phone 8. So for anything below that GetTimeZoneInformation is better.
However another issue is both sometimes return StandardName or DaylightName empty.
In that case you have to use the windows registry as marcinj has stated. Here is the function taken from gnu cash which was also modified from glib.
static std::string
windows_default_tzname(void)
{
const char *subkey =
"SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation";
constexpr size_t keysize{128};
HKEY key;
char key_name[keysize]{};
unsigned long tz_keysize = keysize;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, subkey, 0,
KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
{
if (RegQueryValueExA(key, "TimeZoneKeyName", nullptr, nullptr,
(LPBYTE)key_name, &tz_keysize) != ERROR_SUCCESS)
{
memset(key_name, 0, tz_keysize);
}
RegCloseKey(key);
}
return std::string(key_name);
}
This can be done with the Windows Runtime (WinRT) API, specifically the Calendar.GetTimeZone method. I don't have the C++ code to do so, but here it is with Rust/WinRT version 0.7 from the Rust crate iana-time-zone. The C++ version will be similar.
use windows::globalization::Calendar;
let cal = Calendar::new()?;
let tz_hstring = cal.get_time_zone()?;
# convert the Windows HString to a Rust std::string::String
tz_hstring.to_string()

Convert UTC time into CString format

I need to get the current system time in Unix UTC format and convert it into a CString. I am trying to do this like this
CTime time = CTime::GetCurrentTime();
CString string = time.FormatGmt(L"%d");
code is running, but 'string' variable contains a wrong value, it should contain something like '1011173512', i.e. time in seconds since 1970. Does anyone has any clue why???
The function CTime::FormatGmt uses the same formatting rules as strftime.
https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx
In particular, %d means "Day of month as decimal number (01 – 31)".
I suspect that you want a time_t or similar object. I suggest you want the GetTime method, which returns a _time64_t.
https://msdn.microsoft.com/en-us/library/3s7y67z7.aspx
So:
CTime time = CTime::GetCurrentTime();
CString string; string.Format(L"%lld", time.GetTime());

C++ store and retrieve UTC time with DST info to/from database

I´m using C++ under Linux and I confess that after reading so many posts on the theme I´m litte confused around time_t, struct tm, time, ctime and strftime.
What I need to do is to get the current system date/time, convert it to UTC and store in database. Later on I need to retrieve that date/time and print on screen in a human readable format.
I´m using Oracle (TIMESTAMP), mySQL (DATETIME) and Sqlite3 (has no datetime field, stored either on a INT or a VARCHAR()).
The most important is that I need to store date/time with current time zone considering the DST time, as when I get back the result I can recover the original time zone of the DST for correct information display.
Something like:
// Get current time
std::time_t now = std::time(0);
// Convert it to Oracle ???
? oracletime = ?;
// Convert it to mySQl ???
? mysqltime = ?;
// store it on Sqlite3
int sqlite3time = now;
// print the time
std::cout << now << std::endl;
What would be the correct conversion steps here ?
Thanks for helping.

getting the local system date time and converting it to a string (MFC C++)

I have inherited some MFC C++ code (it's an ActiveX OCX control running on a Windows Mobile 6.5 device) and I need to acquire the system date and time and append it as part of an existing string which gets passed via the com port to another device.
I can get the system date and time, but I can not figure out how to convert that into a string so that I can append it (via strcat.)
I've found a number of different answers on Google and Bing for what at first glance seemed like such a simple problem... :( but I don't know enough MFC C++ to adapt any of it to my needs. Any help would be greatly appreciated.
CTime t = CTime::GetCurrentTime();
CString s = t.Format( "%A, %B %d, %Y" );
char * str = (LPCTSTR) s;
Note, I believe that str is only valid while s is in scope. Probably should copy it off somewhere if you need it to be around after s is destroyed. If you are passing it to strcat() you're probably OK.
In MFC the following code is for current date in MMDDYYYY format.
CTime t = CTime::GetCurrentTime();
CString strDate = t.Format("%m%d%Y");