Fix code and tests so that SubtitleString::v_position is between 0 and 1 (not a perce...
[libdcp.git] / src / local_time.cc
index 665d5d413def2b0b78fc96ff9b74d99038db8184..fe58c07736388622d60b0d90e20c832044d584e1 100644 (file)
@@ -20,6 +20,7 @@
 #include "local_time.h"
 #include "exceptions.h"
 #include <boost/lexical_cast.hpp>
+#include <boost/date_time/c_local_time_adjustor.hpp>
 #include <cstdio>
 
 using std::string;
@@ -30,6 +31,7 @@ LocalTime::LocalTime ()
 {
        time_t now = time (0);
        struct tm* tm = localtime (&now);
+
        _year = tm->tm_year + 1900;
        _month = tm->tm_mon + 1;
        _day = tm->tm_mday + 1;
@@ -37,25 +39,30 @@ LocalTime::LocalTime ()
        _minute = tm->tm_min;
        _second = tm->tm_sec;
 
-       int offset = 0;
-       
-#ifdef LIBDCP_POSIX
-       offset = tm->tm_gmtoff / 60;
-#else
-       TIME_ZONE_INFORMATION tz;
-       GetTimeZoneInformation (&tz);
-       offset = tz.Bias;
-#endif
+       set_local_time_zone ();
+}
 
-       bool const negative = offset < 0;
-       offset = negative ? -offset : offset;
+LocalTime::LocalTime (boost::posix_time::ptime t)
+{
+       _year = t.date().year ();
+       _month = t.date().month ();
+       _day = t.date().day ();
+       _hour = t.time_of_day().hours ();
+       _minute = t.time_of_day().minutes ();
+       _second = t.time_of_day().seconds ();
 
-       _tz_hour = offset / 60;
-       _tz_minute = offset % 60;
+       set_local_time_zone ();
+}
 
-       if (negative) {
-               _tz_hour = -_tz_hour;
-       }
+void
+LocalTime::set_local_time_zone ()
+{
+       boost::posix_time::ptime const utc_now = boost::posix_time::second_clock::universal_time ();
+       boost::posix_time::ptime const now = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local (utc_now);
+       boost::posix_time::time_duration offset = now - utc_now;
+
+       _tz_hour = offset.hours ();
+       _tz_minute = offset.minutes ();
 }
 
 /** @param s A string of the form 2013-01-05T18:06:59+04:00 */
@@ -95,8 +102,24 @@ LocalTime::as_string () const
        char buffer[32];
        snprintf (
                buffer, sizeof (buffer),
-               "%04d-%02d-%02dT%02d:%02d:%02d%s%02d:%02d",
-               _year, _month, _day, _hour, _minute, _second, (_tz_hour >= 0 ? "+" : "-"), abs (_tz_hour), _tz_minute
+               "%sT%s%s%02d:%02d",
+               date().c_str(), time_of_day().c_str(), (_tz_hour >= 0 ? "+" : "-"), abs (_tz_hour), _tz_minute
                );
        return buffer;
 }
+
+string
+LocalTime::date () const
+{
+       char buffer[32];
+       snprintf (buffer, sizeof (buffer), "%04d-%02d-%02d", _year, _month, _day);
+       return buffer;
+}
+
+string
+LocalTime::time_of_day () const
+{
+       char buffer[32];
+       snprintf (buffer, sizeof (buffer), "%02d:%02d:%02d", _hour, _minute, _second);
+       return buffer;
+}