Date.cc
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00012 #include <iostream>
00013
00014
00015 #include "zypp/base/String.h"
00016
00017 #include "zypp/Date.h"
00018
00019 using std::endl;
00020
00022 namespace zypp
00023 {
00024
00025 static std::string adjustLocale();
00026 static void restoreLocale(const std::string & locale);
00027
00029
00030
00031
00032
00033 Date::Date( const std::string & seconds_r )
00034 { str::strtonum( seconds_r, _date ); }
00035
00036 Date::Date( const std::string & date_str, const std::string & format )
00037 : _date(0)
00038 {
00039 struct tm tm = {0};
00040 std::string thisLocale = adjustLocale();
00041
00042 char * res = ::strptime( date_str.c_str(), format.c_str(), &tm );
00043 if ( res != NULL )
00044 _date = ::timelocal( &tm );
00045
00046 restoreLocale(thisLocale);
00047
00048 if (res == NULL)
00049 throw DateFormatException(
00050 str::form( "Invalid date format: '%s'", date_str.c_str() ) );
00051 }
00052
00054
00055
00056
00057
00058 std::string Date::form( const std::string & format_r ) const
00059 {
00060 static char buf[1024];
00061 std::string thisLocale = adjustLocale();
00062
00063 if ( ! strftime( buf, 1024, format_r.c_str(), localtime( &_date ) ) )
00064 *buf = '\0';
00065
00066 restoreLocale(thisLocale);
00067
00068 return buf;
00069 }
00070
00071 static std::string adjustLocale()
00072 {
00073 const char * tmp = ::setlocale( LC_TIME, NULL );
00074 std::string thisLocale( tmp ? tmp : "" );
00075
00076 if ( thisLocale.find( "UTF-8" ) == std::string::npos
00077 && thisLocale.find( "utf-8" ) == std::string::npos
00078 && thisLocale != "POSIX"
00079 && thisLocale != "C"
00080 && thisLocale != "" )
00081 {
00082
00083
00084 std::string needLocale = ".UTF-8";
00085 std::string::size_type loc = thisLocale.find_first_of( ".@" );
00086 if ( loc != std::string::npos )
00087 {
00088
00089 needLocale = thisLocale.substr( 0, loc ) + needLocale;
00090 loc = thisLocale.find_last_of( "@" );
00091 if ( loc != std::string::npos )
00092 {
00093
00094 needLocale += thisLocale.substr( loc );
00095 }
00096 }
00097 else
00098 {
00099
00100 needLocale = thisLocale + needLocale;
00101 }
00102 ::setlocale( LC_TIME, needLocale.c_str() );
00103 }
00104 else
00105 {
00106
00107 thisLocale.clear();
00108 }
00109
00110 return thisLocale;
00111 }
00112
00113 static void restoreLocale(const std::string & locale)
00114 {
00115 if ( ! locale.empty() )
00116 ::setlocale( LC_TIME, locale.c_str() );
00117 }
00118
00120 }