2012-07-11 106 views
0

我有一個傳入的數據饋送,它給了我一個int,其中包含自午夜以來的毫秒數。將午夜以後的毫秒數轉換爲時間對象

我想將其轉換爲某種時間對象,以便我可以顯示時間。

例如,1000 = 00:00:01

有沒有一種簡單的方法來做到這一點?我需要一個時間結構?

謝謝!

+0

是否需要特定的東西嗎?上午/下午或類似的東西? – 2012-07-11 20:51:52

回答

1
x = ms/1000 
seconds = x % 60 
x /= 60 
minutes = x % 60 
x /= 60 
hours = x % 24 

然後你可以cout爲你解析的時間。這只是自午夜以來的持續時間。它不會顯示日期。

1

你可以使用這個小幫手結構,但是這可能是一點點多爲你簡單的要求:

#include <iostream> 
#include <iomanip>  

struct MidnightTime{ 
    MidnightTime(unsigned int miliseconds) : 
    seconds((miliseconds/1000) % 60), 
    minutes((miliseconds/60000) % 60), 
    hours((miliseconds/3600000) % 24){} 

    unsigned int seconds, minutes, hours; 
}; 

std::ostream& operator<<(std::ostream& out, const MidnightTime& t){ 
    out << std::setfill('0') << std::setw(2) << t.hours << ":" << 
      std::setfill('0') << std::setw(2) << t.minutes << ":" << 
      std::setfill('0') << std::setw(2) << t.seconds; 
    return out; 
} 

int main(){ 
    std::cout << MidnightTime(1000) << std::endl; // will result in 00:00:01 
    return 0; 
}