00001 #ifndef TIME_H
00002 #define TIME_H TIME_H
00003 #include <iostream>
00004 #include <iomanip>
00005 #include <string>
00006 #include <sstream>
00007 #include <time.h>
00008
00009
00011
00012 class Time{
00013 public:
00014 Time(int timestamp_ = 0) : timestamp(timestamp_){}
00015 static Time fromBigEndianChars32(const unsigned char* start){
00016 return Time((start[0] << 24) + (start[1] << 16) + (start[2] << 8) + start[3]);
00017 }
00018 string str(const std::string& format = "%c %Z") const{
00019 if(timestamp == -1) return "(undefined)";
00020 char buffer[35];
00021 time_t t = timestamp;
00022 tm* timeinfo = gmtime(&t);
00023 strftime(buffer, 35, format.c_str(), timeinfo);
00024 return buffer;
00025 }
00026 string datestr() const{
00027 return str("%F");
00028 }
00029 friend std::ostream& operator<<(std::ostream& o, const Time& d){
00030 return o << d.str();
00031 }
00032 bool operator>(const Time& other) const{ return timestamp > other.timestamp; }
00033 bool operator<(const Time& other) const{ return timestamp < other.timestamp; }
00034 int timestamp;
00035 };
00036
00038 class Duration{
00039 public:
00041 Duration(int length_ = 0) : length(length_){}
00042 string str() const{
00043 ostringstream o;
00044 o << (*this);
00045 return o.str();
00046 }
00047 friend std::ostream& operator<<(std::ostream& o, const Duration& d){
00048 int l = d.length;
00049 if(l < 0){
00050 o << "-";
00051 l = -l;
00052 }
00053 return o << (l / 3600) << ":" << std::setw(2) << std::setfill('0') << ((l / 60) % 60) << ":" << std::setw(2) << std::setfill('0') << (l % 60);
00054 }
00055 int length;
00056 };
00057
00058 Duration operator-(const Time& a, const Time& b){
00059 return Duration(a.timestamp - b.timestamp);
00060 }
00061
00062 string formatMinutes(int minutes){
00063 ostringstream o;
00064 if(minutes < 24*60)
00065 o << std::setw(2) << std::setfill('0') << (minutes / 60) << ":" << std::setw(2) << std::setfill('0') << (minutes % 60);
00066 else o << (minutes / (24*60)) << " days " << (minutes / (24*60*60)) << " h " << ((minutes / (24*60)) % 60) << " m";
00067 return o.str();
00068 }
00069
00070
00071 #endif