2012-02-20 10 views
5

Dadacómo redondear hasta la siguiente hora dado un impulso :: :: posix_time ptime

boost::posix_time::ptime aTime(time_from_string("2012-01-01 11:15:00")); 

Mi función volverá 2012-01-01 12:00:00

o caso límite determinado :

boost::posix_time::ptime boundaryTime(time_from_string("2012-01-01 23:45:00")); 

Mi función volverá

2012-01-02 00:00:00 
+0

¿Puede haber fracciones de segundo? ¿Quieres ignorar los segundos fraccionarios? –

+0

¿Qué pasa si 'aTime' ya es exactamente en la hora? –

Respuesta

3

Aquí hay un ejemplo. Supuse que los segundos fraccionarios deberían ignorarse. También asumí que si el tiempo original ya era exactamente de una hora, entonces no es necesario incrementarlo a la siguiente hora.

#include <iostream> 
#include <boost/date_time/posix_time/posix_time.hpp> 

namespace bpt = boost::posix_time; 

bpt::ptime roundedToNextHour(const bpt::ptime& time) 
{ 
    // Get time-of-day portion of the time, ignoring fractional seconds 
    bpt::time_duration tod = bpt::seconds(time.time_of_day().total_seconds()); 

    // Round time-of-day down to start of the hour 
    bpt::time_duration roundedDownTod = bpt::hours(tod.hours()); 

    // Construct the result with the same date, but with the rounded-down 
    // time-of-day. 
    bpt::ptime result(time.date(), roundedDownTod); 

    // If the original time was not already on the hour, add one-hour to the 
    // result. Boost knows how to handle the case where time overflows to the 
    // next day. 
    if (tod != roundedDownTod) 
     result += bpt::hours(1); 

    return result; 
} 

int main() 
{ 
    bpt::ptime aTime(bpt::time_from_string("2012-01-01 11:15:00")); 
    bpt::ptime boundaryTime(bpt::time_from_string("2012-01-01 23:45:00")); 
    bpt::ptime onTheHour(bpt::time_from_string("2012-01-01 23:00:00")); 

    std::cout << roundedToNextHour(aTime) << "\n"; 
    std::cout << roundedToNextHour(boundaryTime) << "\n"; 
    std::cout << roundedToNextHour(onTheHour) << "\n"; 
} 

Salida:

2012-Jan-01 12:00:00 
2012-Jan-02 00:00:00 
2012-Jan-01 23:00:00 

espero que este ejemplo ayudó a aprender cómo funciona Boost Posix de tiempo.

+0

Implementé esto usando to_tim para convertir a una estructura tm. Me pareció extraño que no pudiera preguntarle a la ptime por sus componentes. Tu ejemplo me muestra cómo hacerlo. ¡Gracias! – John

Cuestiones relacionadas