In logging I want to add a log entry time in format: GGYG.MM.DD. // CC.MM.SS // mmm,
where MMM is milliseconds.
Can I make it with C++ without manual recalculation of seconds since 1900? This refers to learn all the date entirely. Milliseconds are understandable, considered separately.
Answer 1, Authority 100%
Solution for Windows with “honest” milliseconds:
# include & lt; windows.h & gt;
#Include & lt; stdio.h & gt;
INT MAIN ()
{
SystemTime ST;
Getlocaltime (& amp; ST);
PrintF ("% D-% 02D-% 02D% 02D:% 02D:% 02D.% 03D",
ST.WYEAR,
ST.WMONTH,
ST.WDay,
St.Whour,
st.Wminute
St.Wsecond,
st.wmilliseconds);
}
2016-04-13 18: 26: 45.266
execution result kbd>
Answer 2, Authority 67%
# include & lt; chrono & gt;
Using Namespace Std :: Chrono;
// Main ...
Milliseconds MS = DURATION_CAST & LT; Milliseconds & gt; (
System_Clock :: Now (). Time_Since_epoch ()
);
Answer 3, Authority 67%
For * NIX (checked in Ubuntu) and Windows (checked in MingW), you can use POSIX.1-2001 GetTimeofday (though, already outdated to 8th year, with recommendation POSIX.1-2008 use Clock_getTime (which is missing in Mingw available to me)).
# include & lt; stdlib.h & gt;
#Include & lt; stdio.h & gt;
#Include & lt; Time.h & gt;
#Include & lt; sys / time.h & gt;
#Define Datefmt "yyyy.mm.dd // HH: MM: SS // mmm"
#ifdef win32.
Struct TM *
GMTime_R (TIME_T * T, STRUCT TM * R)
{
STRUCT TM * Res = GMTime (T);
if (res) {
* R = * Res;
res = r;
}
Return R;
}
Struct TM *
Localtime_R (Time_t * T, Struct TM * R)
{
STRUCT TM * Res = Localtime (T);
if (res) {
* R = * Res;
res = r;
}
Return R;
}
#Endif
int.
Main (Int AC, char ** AV)
{
STRUCT TIMEVAL TV;
STRUCT TIMEZONE TZ;
Struct TM TM;
GetTimeOFDay (& amp; TV, & amp; tz); // instead of tz you can 0 if you yourself are not going to play with TZ
// GMTime_R (& amp; tv.tv_sec, & amp; tm); // UTC.
Localtime_R (& amp; TV.tv_sec, & amp; TM);
Char Now [Sizeof (DateFMT) + 1] = "Strftime () error";
Size_t L = STRFTime (NOW, SIZEOF (NOW), "% y.% m.% d //% H.% M.% S //", & amp; TM);
if (L)
SPRINTF (NOW + L, "% 03D", (int) TV.tv_usec / 1000); // I think that in such tasks rounding is too
RETURN PUTS (NOW) == EOF;
}
It turns out that there is no localtime_r ()
/ gmtime_r ()
also strftime ()
in Windows does not understand % G
and % T
.
Answer 4, Authority 33%
It is suitable for a solution only for Windows?
/ * straftime example * /
#Include & lt; stdio.h & gt; / * Puts * /
#Include & lt; Time.h & gt; / * Time_T, Struct TM, Time, Localtime, Strftime * /
#Include & lt; Windows.h & gt;
INT MAIN ()
{
Time_t Rawtime;
Struct TM * TimeInfo;
Char Buffer [80];
Time (& amp; rawtime);
TimeInfo = Localtime (& amp; rawtime);
Strftime (Buffer, 80, "NOW IT'S% Y.% m.% d //% H.% M.% S //", timeinfo);
PrintF ("% s", buffer);
PrintF ("% d \ n", gettickcount ()% 1000);
Return 0;
}