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
00010
00011 class Time{
00012 public:
00013 Time(int timestamp_ = 0) : timestamp(timestamp_){}
00014 static Time fromBigEndianChars32(const unsigned char* start){
00015 return Time((start[0] << 24) + (start[1] << 16) + (start[2] << 8) + start[3]);
00016 }
00017 string str(const std::string& format = "%c") const{
00018 if(timestamp == -1) return "(undefined)";
00019 char buffer[40];
00020 time_t t = timestamp;
00021 tm* timeinfo = gmtime(&t);
00022 strftime(buffer, 39, format.c_str(), timeinfo);
00023 return buffer;
00024 }
00025 string datestr() const{
00026 return str("%x");
00027 }
00028 friend std::ostream& operator<<(std::ostream& o, const Time& d){
00029 return o << d.str();
00030 }
00031 bool operator>(const Time& other) const{ return timestamp > other.timestamp; }
00032 bool operator<(const Time& other) const{ return timestamp < other.timestamp; }
00033 int timestamp;
00034 };
00035
00037 class Duration{
00038 public:
00040 Duration(int length_ = 0) : length(length_){}
00041 string str() const{
00042 ostringstream o;
00043 o << (*this);
00044 return o.str();
00045 }
00046 friend std::ostream& operator<<(std::ostream& o, const Duration& d){
00047 int l = d.length;
00048 if(l < 0){
00049 o << "-";
00050 l = -l;
00051 }
00052 if(l > 86400){
00053 o << (l / 86400) << " " << tr("days") << " ";
00054 l %= 86400;
00055 }
00056 return o << (l / 3600) << ":" << std::setw(2) << std::setfill('0') << ((l / 60) % 60) << ":" << std::setw(2) << std::setfill('0') << (l % 60);
00057 }
00058 int length;
00059 };
00060
00061 Duration operator-(const Time& a, const Time& b){
00062 return Duration(a.timestamp - b.timestamp);
00063 }
00064
00065 string formatRange(const Time& begin, const Time& end){
00066 Duration d = end - begin;
00067 if(d.length < 86400) return tr("from") + " " + begin.str() + " " + tr("on for") + " " + d.str();
00068 return tr("from") + " " + begin.str() + " " + tr("to") + " " + end.str() + " (" + d.str() + ")";
00069 }
00070
00071 string formatMinutes(int minutes){
00072 ostringstream o;
00073 if(minutes < 24*60)
00074 o << std::setw(2) << std::setfill('0') << (minutes / 60) << ":" << std::setw(2) << std::setfill('0') << (minutes % 60);
00075 else o << (minutes / (24*60)) << " days " << (minutes / (24*60*60)) << " h " << ((minutes / (24*60)) % 60) << " min";
00076 return o.str();
00077 }
00078
00079
00080 #endif