1

I have a c++ class code which return a local time:

SYSTEMTIME sm;
GetLocalTime( &sm );

but sm.wHour always returns an hour in 24 format, it doesn't concern my windows os time format settings!! (ie. use 24 or 12 time format).

How can I get a local time hour according to my windows os time format settings?

Bassam Najeeb
  • 607
  • 2
  • 7
  • 16

1 Answers1

1

Just found GetDateFormatA is outdated, you should use GetDateFormatEx

Simple example:

#include <windows.h>
#include <iostream>
#include <io.h>
#include <fcntl.h>

int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);

    const int len = 50;
    LPWSTR date = new WCHAR[len];
    GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, DATE_AUTOLAYOUT, NULL, NULL, date, len, NULL);

    LPWSTR time = new WCHAR[len];
    GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, 0, NULL, NULL, time, len );

    std::wcout << date << std::endl << time;
    return 0;
}

If you have question about the api parameters, you may find GetDateFormatEx and GetTimeFormatEx in msdn are useful.

For _setmode(_fileno(stdout), _O_U16TEXT);, it's a hack to print unicode under windows console. You may refer to this answer

Note WinApis above depend on long time format, not short time format.

Though I couldn't find api for short time format. If you want a time format no including seconds, use TIME_NOSECONDS instead of LOCALE_NAME_USER_DEFAULT.

Louis Go
  • 2,213
  • 2
  • 16
  • 29
  • I have tested this code and this always display in 12 time format even I change my time settings OS to 24 format – Bassam Najeeb Jul 29 '20 at 11:48
  • @BassamNajeeb There are two kind of DateTime format in windows. One is short and another is long. After I tested, GetTimeFormatEx depends on long format. If you're win10, refer to this [link](https://www.windowscentral.com/how-change-date-and-time-formats-windows-10) to change format. – Louis Go Jul 29 '20 at 11:55
  • thanks, it works right with long format, any way run it with short format settings ? – Bassam Najeeb Aug 09 '20 at 12:54
  • I did not found any related topic about it. You may post your answer if you found it. Though I'd suggest to take a step back asking "why short time format is needed?" If long time format is too long, passing `TIME_NOMINUTESORSECONDS` would get you a string without seconds. – Louis Go Aug 10 '20 at 00:51
  • My problem is a Windows OS take a time format from a "short time format" option, and a user see a side effect of this option at a right corner of a task bar, so I want from my software also take this option rather than a long time format, i.e make it a single option and be an identical to Win OS. – Bassam Najeeb Aug 10 '20 at 08:35
  • @BassamNajeeb Your best shot is getting registry of `\HKEY_CURRENT_USER\Control Panel\International\sShortTime` for string format. – Louis Go Aug 10 '20 at 09:14