1 // This is core/vul/vul_get_timestamp.cxx
2 //:
3 // \file
4 // \author fsm
5
6 #include <ctime>
7 #include <sstream>
8 #include <iomanip>
9 #include "vul_get_timestamp.h"
10
11 #ifdef _MSC_VER
12 # include "vcl_msvc_warnings.h"
13 #endif
14
15 #if defined(_WIN32) && !defined(__CYGWIN__)
16 # include <direct.h>
17 #else
18 # include <unistd.h> // for struct timeval
19 #endif
20
21 #include <vcl_sys/time.h> // for gettimeofday()
22
23 // for vul_get_time_string()
24 #include "vul/vul_string.h"
25 //
26
27 #if !defined(_WIN32) || defined(__CYGWIN__)
28 // POSIX
29 void
vul_get_timestamp(int & secs,int & msecs)30 vul_get_timestamp(int & secs, int & msecs)
31 {
32 struct timeval timestamp;
33 struct timezone * dummy = nullptr;
34 gettimeofday(×tamp, dummy);
35
36 secs = timestamp.tv_sec;
37 msecs = timestamp.tv_usec / 1000;
38 }
39 #else
40 // _WIN32 and not __CYGWIN__
41 void
vul_get_timestamp(int & secs,int & msecs)42 vul_get_timestamp(int & secs, int & msecs)
43 {
44 struct _timeb real;
45 _ftime(&real);
46
47 secs = static_cast<int>(real.time);
48 msecs = real.millitm;
49 }
50 #endif
51
52
53 // Get the present time and date as a string, e.g. "Fri Dec 8 14:54:17 2006"
54 std::string
vul_get_time_as_string(vul_time_style style)55 vul_get_time_as_string(vul_time_style style /*default=vul_asc*/)
56 {
57 std::string timestr;
58
59 // Get time in seconds since Jan 1 1970
60 std::time_t time_secs;
61 std::time(&time_secs);
62
63 // Convert time to struct tm form
64 struct std::tm * time;
65 time = std::localtime(&time_secs);
66
67 switch (style)
68 {
69 case vul_numeric_msf: {
70 // Express as a series of space-separated numbers, most significant first
71 // e.g. yyyy mm dd hh mm ss
72 // NB Month, day start at 1. Hour, minute, second start at 0.
73 // Leading zeros are used for single-digit month,day,hour,min,sec.
74 std::ostringstream oss;
75 oss.fill('0');
76 oss << std::setw(4) << 1900 + time->tm_year << ' ' << std::setw(2) << 1 + time->tm_mon << ' ' << std::setw(2)
77 << time->tm_mday << ' ' << std::setw(2) << time->tm_hour << ' ' << std::setw(2) << time->tm_min << ' '
78 << std::setw(2) << time->tm_sec;
79 timestr = oss.str();
80 }
81 break;
82
83 default: {
84 // Get local time & date using standard asctime() function,
85 // Removes the trailing eol that asctime() inserts.
86 timestr = std::asctime(time);
87 vul_string_right_trim(timestr, "\n");
88 }
89 break;
90 }
91
92 return timestr;
93 }
94