Search code examples
c++datetimelocaleunix-timestamppoco-libraries

Poco DateTimeFormatter - Print timestamp with current timezone


How do I print a Poco::Timestamp with Poco::DateTimeFormatter into a formatted date-time based on the current timezone?

I have a print_pretty_datetime(const Poco::Timestamp &now) where I'll receive a Poco::Timestamp so I can't use a Poco::LocalDateTime unfortunately.

MCVE:

#include "Poco/Timestamp.h"
#include "Poco/Timezone.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"

#include <iostream>
#include <string>

// Cannot change the method signature. I will receive a Poco::Timestamp object
std::string print_pretty_datetime(const Poco::Timestamp &now)
{
    return Poco::DateTimeFormatter::format(
       now,
       Poco::DateTimeFormat::SORTABLE_FORMAT,
       Poco::Timezone::tzd()
     );
}


int main()
{
     Poco::Timestamp now;
     std::string dt_now = print_pretty_datetime(now);

     std::cout << dt_now << '\n';

     return 0;
}

E.g: the string returned is 2019-01-07 11:10:12 (thus UTC+0) whereas my device is in in UTC+1.

In fact, the command date returns Mon Jan 7 12.10.12 CET 2019.

What is the correct parameter for tzd in Poco::DateTimeFormatter::format for printing the date-time based on current locale?


System info:

SMP Debian 4.9.130-2 (2018-10-27) x86_64 GNU/Linux
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Poco 1.9.0

Solution

  • You can create a Poco::LocalDateTime in the system's current timezone from a Poco::Timestamp via an intermediate Poco::DateTime object.

    #include "Poco/LocalDateTime.h"
    #include "Poco/DateTime.h"
    #include "Poco/DateTimeFormat.h"
    #include "Poco/DateTimeFormatter.h"
    #include <iostream>
    
    int main(int argc, char** argv)
    {
        Poco::Timestamp ts;
        Poco::DateTime dt(ts);
        Poco::LocalDateTime ldt(dt);
    
        std::string str = Poco::DateTimeFormatter::format(ldt, Poco::DateTimeFormat::SORTABLE_FORMAT);
        std::cout << str << std::endl;
    
        return 0;
    }