File: TimeStr.cpp

package info (click to toggle)
librepfunc 1.11.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 468 kB
  • sloc: cpp: 1,768; makefile: 270
file content (38 lines) | stat: -rw-r--r-- 1,165 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*******************************************************************************
 * librepfunc - a collection of common functions, classes and tools.
 * See the README file for copyright information and how to reach the author.
 ******************************************************************************/
#include <sstream>   // std:.stringstream
#include <iomanip>   // std::setfill, std::setw, std::right
#include <ctime>     // time_t, time(), ..
#include <repfunc.h> // include this library

std::string TimeStr(std::intmax_t t) {
  auto IntToStr = [](std::intmax_t n, size_t width) {
     std::stringstream ss;
     ss << std::setfill('0') << std::setw(width) << std::right << n;
     return ss.str();
     };

  time_t aTime;

  if (t == 0)
     aTime = time(nullptr);
  else
     aTime = (time_t) t;

  struct tm buf;
  struct tm* tm = localtime_r(&aTime, &buf);

  return IntToStr(tm->tm_mday,2) +
         '.' +
         IntToStr(1+tm->tm_mon,2) +
         '.' +
         IntToStr(1900+tm->tm_year,4) +
         ' ' +
         IntToStr(tm->tm_hour,2) +
         ':' +
         IntToStr(tm->tm_min,2) +
         ':' +
         IntToStr(tm->tm_sec,2);
}