more timezone stuff - it's a miracle, but it seems to work

git-svn-id: https://svn.wxwidgets.org/svn/wx/wxWidgets/trunk@4896 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
This commit is contained in:
Vadim Zeitlin
1999-12-10 20:44:37 +00:00
parent e4b8154a65
commit 299fcbfe98
4 changed files with 316 additions and 160 deletions

View File

@@ -37,13 +37,14 @@ class WXDLLEXPORT wxDateSpan;
/* /*
* TODO Well, everything :-) * TODO Well, everything :-)
* *
* 1. Time zones with minutes (make wxTimeZone a class) * + 1. Time zones with minutes (make TimeZone a class)
* 2. getdate() function like under Solaris * 2. getdate() function like under Solaris
* 3. text conversion for wxDateSpan * + 3. text conversion for wxDateSpan
* 4. pluggable modules for the workdays calculations
*/ */
/* /*
The three classes declared in this header represent: The three (main) classes declared in this header represent:
1. An absolute moment in the time (wxDateTime) 1. An absolute moment in the time (wxDateTime)
2. A difference between two moments in the time, positive or negative 2. A difference between two moments in the time, positive or negative
@@ -322,6 +323,21 @@ public:
// helper classes // helper classes
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// a class representing a time zone: basicly, this is just an offset
// (in seconds) from GMT
class TimeZone
{
public:
TimeZone(TZ tz);
TimeZone(wxDateTime_t offset = 0) { m_offset = offset; }
int GetOffset() const { return m_offset; }
private:
// offset for this timezone from GMT in seconds
int m_offset;
};
// standard struct tm is limited to the years from 1900 (because // standard struct tm is limited to the years from 1900 (because
// tm_year field is the offset from 1900), so we use our own struct // tm_year field is the offset from 1900), so we use our own struct
// instead to represent broken down time // instead to represent broken down time
@@ -338,8 +354,8 @@ public:
// default ctor inits the object to an invalid value // default ctor inits the object to an invalid value
Tm(); Tm();
// ctor from struct tm // ctor from struct tm and the timezone
Tm(const struct tm& tm); Tm(const struct tm& tm, const TimeZone& tz);
// check that the given date/time is valid (in Gregorian calendar) // check that the given date/time is valid (in Gregorian calendar)
bool IsValid() const; bool IsValid() const;
@@ -363,26 +379,14 @@ public:
// compute the weekday from other fields // compute the weekday from other fields
void ComputeWeekDay(); void ComputeWeekDay();
// the timezone we correspond to
TimeZone m_tz;
// these values can't be accessed directly because they're not always // these values can't be accessed directly because they're not always
// computed and we calculate them on demand // computed and we calculate them on demand
wxDateTime_t wday, yday; wxDateTime_t wday, yday;
}; };
// a class representing a time zone: basicly, this is just an offset
// (in minutes) from GMT
class TimeZone
{
public:
TimeZone(TZ tz);
TimeZone(wxDateTime_t offset) { m_offset = offset; }
int GetOffset() const { return m_offset; }
private:
// offset for this timezone from GMT in minutes
int m_offset;
};
// static methods // static methods
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
@@ -442,9 +446,6 @@ public:
// constructors: you should test whether the constructor succeeded with // constructors: you should test whether the constructor succeeded with
// IsValid() function. The values Inv_Month and Inv_Year for the // IsValid() function. The values Inv_Month and Inv_Year for the
// parameters mean take current month and/or year values. // parameters mean take current month and/or year values.
//
// All new wxDateTime correspond to the local time, use ToUTC() or
// MakeUTC() to get the time in UTC/GMT.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// default ctor does not initialize the object, use Set()! // default ctor does not initialize the object, use Set()!
@@ -607,27 +608,21 @@ public:
// religious holidays (Easter...) or moon/solar eclipses? Some // religious holidays (Easter...) or moon/solar eclipses? Some
// algorithms can be found in the calendar FAQ // algorithms can be found in the calendar FAQ
// timezone stuff: by default, we always work with local times, to get // timezone stuff: a wxDateTime object constructed using given
// anything else, it should be requested explicitly // day/month/year/hour/min/sec values correspond to this moment in local
// time. Using the functions below, it may be converted to another time
// zone (for example, the Unix epoch is wxDateTime(1, Jan, 1970).ToGMT())
//
// Converting to the local time zone doesn't do anything.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// transform this object to UTC/GMT // transform to any given timezone
wxDateTime& MakeUTC();
wxDateTime& MakeGMT() { return MakeUTC(); }
// get the time corresponding to this one in UTC/GMT
inline wxDateTime ToUTC() const;
wxDateTime ToGMT() const { return ToUTC(); }
// generic versions of the above
// transform from local time to any given timezone
inline wxDateTime ToTimezone(const TimeZone& tz) const; inline wxDateTime ToTimezone(const TimeZone& tz) const;
wxDateTime& MakeTimezone(const TimeZone& tz); wxDateTime& MakeTimezone(const TimeZone& tz);
// transform time from any timezone to the local time // transform to GMT/UTC
inline wxDateTime ToLocalTime(const TimeZone& tz) const; wxDateTime ToGMT() const { return ToTimezone(GMT0); }
wxDateTime& MakeLocalTime(const TimeZone& tz); wxDateTime& MakeGMT() { return MakeTimezone(GMT0); }
// accessors: many of them take the timezone parameter which indicates the // accessors: many of them take the timezone parameter which indicates the
// timezone for which to make the calculations and the default value means // timezone for which to make the calculations and the default value means
@@ -640,40 +635,52 @@ public:
// the functions which failed to convert the date to supported range) // the functions which failed to convert the date to supported range)
inline bool IsValid() const { return this != &ms_InvDateTime; } inline bool IsValid() const { return this != &ms_InvDateTime; }
// get the broken down date/time representation // get the broken down date/time representation in the given timezone
Tm GetTm() const; //
// If you wish to get several time components (day, month and year),
// consider getting the whole Tm strcuture first and retrieving the
// value from it - this is much more efficient
Tm GetTm(const TimeZone& tz = Local) const;
// get the number of seconds since the Unix epoch - returns (time_t)-1 // get the number of seconds since the Unix epoch - returns (time_t)-1
// if the value is out of range // if the value is out of range
inline time_t GetTicks() const; inline time_t GetTicks() const;
// get the year (returns Inv_Year if date is invalid) // get the year (returns Inv_Year if date is invalid)
int GetYear() const { return GetTm().year; } int GetYear(const TimeZone& tz = Local) const
{ return GetTm(tz).year; }
// get the month (Inv_Month if date is invalid) // get the month (Inv_Month if date is invalid)
Month GetMonth() const { return (Month)GetTm().mon; } Month GetMonth(const TimeZone& tz = Local) const
{ return (Month)GetTm(tz).mon; }
// get the month day (in 1..31 range, 0 if date is invalid) // get the month day (in 1..31 range, 0 if date is invalid)
wxDateTime_t GetDay() const { return GetTm().mday; } wxDateTime_t GetDay(const TimeZone& tz = Local) const
{ return GetTm(tz).mday; }
// get the day of the week (Inv_WeekDay if date is invalid) // get the day of the week (Inv_WeekDay if date is invalid)
WeekDay GetWeekDay() const { return GetTm().GetWeekDay(); } WeekDay GetWeekDay(const TimeZone& tz = Local) const
{ return GetTm(tz).GetWeekDay(); }
// get the hour of the day // get the hour of the day
wxDateTime_t GetHour() const { return GetTm().hour; } wxDateTime_t GetHour(const TimeZone& tz = Local) const
{ return GetTm(tz).hour; }
// get the minute // get the minute
wxDateTime_t GetMinute() const { return GetTm().min; } wxDateTime_t GetMinute(const TimeZone& tz = Local) const
{ return GetTm(tz).min; }
// get the second // get the second
wxDateTime_t GetSecond() const { return GetTm().sec; } wxDateTime_t GetSecond(const TimeZone& tz = Local) const
{ return GetTm(tz).sec; }
// get milliseconds // get milliseconds
wxDateTime_t GetMillisecond() const { return m_time.GetLo() % 1000; } wxDateTime_t GetMillisecond(const TimeZone& tz = Local) const
{ return GetTm(tz).msec; }
// get the day since the year start (1..366, 0 if date is invalid) // get the day since the year start (1..366, 0 if date is invalid)
wxDateTime_t GetDayOfYear() const; wxDateTime_t GetDayOfYear(const TimeZone& tz = Local) const;
// get the week number since the year start (1..52, 0 if date is // get the week number since the year start (1..52, 0 if date is
// invalid) // invalid)
wxDateTime_t GetWeekOfYear() const; wxDateTime_t GetWeekOfYear(const TimeZone& tz = Local) const;
// is this date a work day? This depends on a country, of course, // is this date a work day? This depends on a country, of course,
// because the holidays are different in different countries // because the holidays are different in different countries
bool IsWorkDay(Country country = Country_Default, bool IsWorkDay(Country country = Country_Default,
TimeZone zone = Local) const; const TimeZone& tz = Local) const;
// is this date later than Gregorian calendar introduction for the // is this date later than Gregorian calendar introduction for the
// given country (see enum GregorianAdoption)? // given country (see enum GregorianAdoption)?
@@ -683,11 +690,12 @@ public:
// adoption of the Gregorian calendar is simply unknown. // adoption of the Gregorian calendar is simply unknown.
bool IsGregorianDate(GregorianAdoption country = Gr_Standard) const; bool IsGregorianDate(GregorianAdoption country = Gr_Standard) const;
// is daylight savings time in effect at this moment? // is daylight savings time in effect at this moment according to the
// rules of the specified country?
// //
// Return value is > 0 if DST is in effect, 0 if it is not and -1 if // Return value is > 0 if DST is in effect, 0 if it is not and -1 if
// the information is not available (this is compatible with ANSI C) // the information is not available (this is compatible with ANSI C)
int IsDST(Country country = Country_Default, TimeZone zone = Local) const; int IsDST(Country country = Country_Default) const;
// comparison (see also functions below for operator versions) // comparison (see also functions below for operator versions)
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
@@ -761,7 +769,8 @@ public:
// argument corresponds to the preferred date and time representation // argument corresponds to the preferred date and time representation
// for the current locale) and returns the string containing the // for the current locale) and returns the string containing the
// resulting text representation // resulting text representation
wxString Format(const wxChar *format = _T("%c")) const; wxString Format(const wxChar *format = _T("%c"),
const TimeZone& tz = Local) const;
// preferred date representation for the current locale // preferred date representation for the current locale
wxString FormatDate() const { return Format(_T("%x")); } wxString FormatDate() const { return Format(_T("%x")); }
// preferred time representation for the current locale // preferred time representation for the current locale
@@ -780,7 +789,7 @@ public:
static struct tm *GetTmNow() static struct tm *GetTmNow()
{ {
time_t t = GetTimeNow(); time_t t = GetTimeNow();
return gmtime(&t); return localtime(&t);
} }
private: private:

View File

@@ -246,21 +246,11 @@ wxDateTime& wxDateTime::operator+=(const wxDateSpan& diff)
// wxDateTime and timezones // wxDateTime and timezones
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxDateTime wxDateTime::ToUTC() const
{
return wxDateTime(*this).MakeUTC();
}
wxDateTime wxDateTime::ToTimezone(const wxDateTime::TimeZone& tz) const wxDateTime wxDateTime::ToTimezone(const wxDateTime::TimeZone& tz) const
{ {
return wxDateTime(*this).MakeTimezone(tz); return wxDateTime(*this).MakeTimezone(tz);
} }
wxDateTime wxDateTime::ToLocalTime(const wxDateTime::TimeZone& tz) const
{
return wxDateTime(*this).MakeLocalTime(tz);
}
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxTimeSpan construction // wxTimeSpan construction
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------

View File

@@ -30,12 +30,12 @@
// what to test? // what to test?
//#define TEST_ARRAYS //#define TEST_ARRAYS
#define TEST_DIR //#define TEST_DIR
//#define TEST_LOG //#define TEST_LOG
//#define TEST_MIME //#define TEST_MIME
//#define TEST_STRINGS //#define TEST_STRINGS
//#define TEST_THREADS //#define TEST_THREADS
//#define TEST_TIME #define TEST_TIME
//#define TEST_LONGLONG //#define TEST_LONGLONG
// ============================================================================ // ============================================================================
@@ -152,6 +152,8 @@ static void TestMimeEnum()
filetype->GetDescription(&desc); filetype->GetDescription(&desc);
filetype->GetExtensions(exts); filetype->GetExtensions(exts);
filetype->GetIcon(NULL);
wxString extsAll; wxString extsAll;
for ( size_t e = 0; e < exts.GetCount(); e++ ) for ( size_t e = 0; e < exts.GetCount(); e++ )
{ {
@@ -252,6 +254,63 @@ static void TestDivision()
#include <wx/datetime.h> #include <wx/datetime.h>
// the test data
struct Date
{
wxDateTime::wxDateTime_t day;
wxDateTime::Month month;
int year;
wxDateTime::wxDateTime_t hour, min, sec;
double jdn;
time_t gmticks, ticks;
void Init(const wxDateTime::Tm& tm)
{
day = tm.mday;
month = tm.mon;
year = tm.year;
hour = tm.hour;
min = tm.min;
sec = tm.sec;
jdn = 0.0;
gmticks = ticks = -1;
}
wxDateTime DT() const
{ return wxDateTime(day, month, year, hour, min, sec); }
wxString Format() const
{
wxString s;
s.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
hour, min, sec,
wxDateTime::GetMonthName(month).c_str(),
day,
abs(wxDateTime::ConvertYearToBC(year)),
year > 0 ? "AD" : "BC");
return s;
}
};
static const Date testDates[] =
{
{ 1, wxDateTime::Jan, 1970, 00, 00, 00, 2440587.5, 0, -3600 },
{ 21, wxDateTime::Jan, 2222, 00, 00, 00, 2532648.5, -1, -1 },
{ 29, wxDateTime::May, 1976, 12, 00, 00, 2442928.0, 202219200, 202212000 },
{ 29, wxDateTime::Feb, 1976, 00, 00, 00, 2442837.5, 194400000, 194396400 },
{ 1, wxDateTime::Jan, 1900, 12, 00, 00, 2415021.0, -1, -1 },
{ 1, wxDateTime::Jan, 1900, 00, 00, 00, 2415020.5, -1, -1 },
{ 15, wxDateTime::Oct, 1582, 00, 00, 00, 2299160.5, -1, -1 },
{ 4, wxDateTime::Oct, 1582, 00, 00, 00, 2299149.5, -1, -1 },
{ 1, wxDateTime::Mar, 1, 00, 00, 00, 1721484.5, -1, -1 },
{ 1, wxDateTime::Jan, 1, 00, 00, 00, 1721425.5, -1, -1 },
{ 31, wxDateTime::Dec, 0, 00, 00, 00, 1721424.5, -1, -1 },
{ 1, wxDateTime::Jan, 0, 00, 00, 00, 1721059.5, -1, -1 },
{ 12, wxDateTime::Aug, -1234, 00, 00, 00, 1270573.5, -1, -1 },
{ 12, wxDateTime::Aug, -4000, 00, 00, 00, 260313.5, -1, -1 },
{ 24, wxDateTime::Nov, -4713, 00, 00, 00, -0.5, -1, -1 },
};
// this test miscellaneous static wxDateTime functions // this test miscellaneous static wxDateTime functions
static void TestTimeStatic() static void TestTimeStatic()
{ {
@@ -300,10 +359,29 @@ static void TestTimeSet()
{ {
puts("\n*** wxDateTime construction test ***"); puts("\n*** wxDateTime construction test ***");
#if 0
printf("Current time:\t%s\n", wxDateTime::Now().Format().c_str()); printf("Current time:\t%s\n", wxDateTime::Now().Format().c_str());
printf("Unix epoch:\t%s\n", wxDateTime((time_t)0).Format().c_str()); printf("Unix epoch:\t%s\n", wxDateTime((time_t)0).Format().c_str());
printf("Today noon:\t%s\n", wxDateTime(12, 0).Format().c_str()); printf("Today noon:\t%s\n", wxDateTime(12, 0).Format().c_str());
printf("May 29, 1976:\t%s\n", wxDateTime(29, wxDateTime::May, 1976).Format().c_str()); printf("May 29, 1976:\t%s\n", wxDateTime(29, wxDateTime::May, 1976).Format().c_str());
printf("Jan 1, 1900:\t%s\n", wxDateTime(1, wxDateTime::Jan, 1900).Format().c_str());
#else
for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
{
const Date& d1 = testDates[n];
wxDateTime dt = d1.DT();
Date d2;
d2.Init(dt.GetTm());
wxString s1 = d1.Format(),
s2 = d2.Format();
printf("Date: %s == %s (%s)\n",
s1.c_str(), s2.c_str(),
s1 == s2 ? "ok" : "ERROR");
}
#endif
} }
// test time zones stuff // test time zones stuff
@@ -313,11 +391,12 @@ static void TestTimeZones()
wxDateTime now = wxDateTime::Now(); wxDateTime now = wxDateTime::Now();
printf("Current GMT time:\t%s\n", now.ToGMT().Format().c_str()); printf("Current GMT time:\t%s\n", now.Format("%c", wxDateTime::GMT0).c_str());
printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).MakeGMT().Format().c_str()); printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0).c_str());
printf("Current time in Paris:\t%s\n", now.ToTimezone(wxDateTime::CET).Format().c_str()); printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST).c_str());
printf(" Moscow:\t%s\n", now.ToTimezone(wxDateTime::MSK).Format().c_str()); printf("Current time in Paris:\t%s\n", now.Format("%c", wxDateTime::CET).c_str());
printf(" New York:\t%s\n", now.ToTimezone(wxDateTime::EST).Format().c_str()); printf(" Moscow:\t%s\n", now.Format("%c", wxDateTime::MSK).c_str());
printf(" New York:\t%s\n", now.Format("%c", wxDateTime::EST).c_str());
} }
// test some minimal support for the dates outside the standard range // test some minimal support for the dates outside the standard range
@@ -337,48 +416,58 @@ static void TestTimeRange()
wxDateTime(29, wxDateTime::May, 2099).Format().c_str()); wxDateTime(29, wxDateTime::May, 2099).Format().c_str());
} }
static void TestTimeTicks()
{
puts("\n*** wxDateTime ticks test ***");
for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
{
const Date& d = testDates[n];
if ( d.ticks == -1 )
continue;
wxDateTime dt = d.DT();
long ticks = (dt.GetValue() / 1000).ToLong();
printf("Ticks of %s:\t% 10ld", d.Format().c_str(), ticks);
if ( ticks == d.ticks )
{
puts(" (ok)");
}
else
{
printf(" (ERROR: should be %ld, delta = %ld)\n",
d.ticks, ticks - d.ticks);
}
dt = d.DT().ToTimezone(wxDateTime::GMT0);
ticks = (dt.GetValue() / 1000).ToLong();
printf("GMtks of %s:\t% 10ld", d.Format().c_str(), ticks);
if ( ticks == d.gmticks )
{
puts(" (ok)");
}
else
{
printf(" (ERROR: should be %ld, delta = %ld)\n",
d.gmticks, ticks - d.gmticks);
}
}
puts("");
}
// test conversions to JDN &c // test conversions to JDN &c
static void TestTimeJDN() static void TestTimeJDN()
{ {
puts("\n*** wxDateTime to JDN test ***"); puts("\n*** wxDateTime to JDN test ***");
struct Date
{
wxDateTime::wxDateTime_t day;
wxDateTime::Month month;
int year;
double jdn;
};
static const Date testDates[] =
{
{ 21, wxDateTime::Jan, 2222, 2532648.5 },
{ 29, wxDateTime::May, 1976, 2442927.5 },
{ 1, wxDateTime::Jan, 1970, 2440587.5 },
{ 1, wxDateTime::Jan, 1900, 2415020.5 },
{ 15, wxDateTime::Oct, 1582, 2299160.5 },
{ 4, wxDateTime::Oct, 1582, 2299149.5 },
{ 1, wxDateTime::Mar, 1, 1721484.5 },
{ 1, wxDateTime::Jan, 1, 1721425.5 },
{ 31, wxDateTime::Dec, 0, 1721424.5 },
{ 1, wxDateTime::Jan, 0, 1721059.5 },
{ 12, wxDateTime::Aug, -1234, 1270573.5 },
{ 12, wxDateTime::Aug, -4000, 260313.5 },
{ 24, wxDateTime::Nov, -4713, -0.5 },
};
for ( size_t n = 0; n < WXSIZEOF(testDates); n++ ) for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
{ {
const Date& d = testDates[n]; const Date& d = testDates[n];
wxDateTime dt(d.day, d.month, d.year); wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
double jdn = dt.GetJulianDayNumber(); double jdn = dt.GetJulianDayNumber();
printf("JDN of %s %02d, %4d%s is:\t%f", printf("JDN of %s is:\t% 15.6f", d.Format().c_str(), jdn);
wxDateTime::GetMonthName(d.month).c_str(),
d.day,
wxDateTime::ConvertYearToBC(d.year),
d.year > 0 ? "AD" : "BC",
jdn);
if ( jdn == d.jdn ) if ( jdn == d.jdn )
{ {
puts(" (ok)"); puts(" (ok)");
@@ -656,7 +745,7 @@ void PrintArray(const char* name, const wxArrayString& array)
#include "wx/timer.h" #include "wx/timer.h"
void TestString() static void TestString()
{ {
wxStopWatch sw; wxStopWatch sw;
@@ -681,7 +770,7 @@ void TestString()
printf ("TestString elapsed time: %ld\n", sw.Time()); printf ("TestString elapsed time: %ld\n", sw.Time());
} }
void TestPChar() static void TestPChar()
{ {
wxStopWatch sw; wxStopWatch sw;
@@ -704,6 +793,23 @@ void TestPChar()
printf ("TestPChar elapsed time: %ld\n", sw.Time()); printf ("TestPChar elapsed time: %ld\n", sw.Time());
} }
static void TestStringSub()
{
wxString s("Hello, world!");
puts("*** Testing wxString substring extraction ***");
printf("String = '%s'\n", s.c_str());
printf("Left(5) = '%s'\n", s.Left(5).c_str());
printf("Right(6) = '%s'\n", s.Right(6).c_str());
printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
printf("Mid(3) = '%s'\n", s.Mid(3).c_str());
printf("substr(3, 5) = '%s'\n", s.substr(3, 5).c_str());
printf("substr(3) = '%s'\n", s.substr(3).c_str());
puts("");
}
#endif // TEST_STRINGS #endif // TEST_STRINGS
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
@@ -718,8 +824,12 @@ int main(int argc, char **argv)
} }
#ifdef TEST_STRINGS #ifdef TEST_STRINGS
if ( 0 )
{
TestPChar(); TestPChar();
TestString(); TestString();
}
TestStringSub();
#endif // TEST_STRINGS #endif // TEST_STRINGS
#ifdef TEST_ARRAYS #ifdef TEST_ARRAYS
@@ -809,11 +919,15 @@ int main(int argc, char **argv)
#endif // TEST_MIME #endif // TEST_MIME
#ifdef TEST_TIME #ifdef TEST_TIME
TestTimeStatic();
TestTimeSet(); TestTimeSet();
if ( 0 )
{
TestTimeStatic();
TestTimeZones(); TestTimeZones();
TestTimeRange(); TestTimeRange();
TestTimeTicks();
TestTimeJDN(); TestTimeJDN();
}
#endif // TEST_TIME #endif // TEST_TIME
wxUninitialize(); wxUninitialize();

View File

@@ -20,7 +20,8 @@
* Implementation notes: * Implementation notes:
* *
* 1. the time is stored as a 64bit integer containing the signed number of * 1. the time is stored as a 64bit integer containing the signed number of
* milliseconds since Jan 1. 1970 (the Unix Epoch) * milliseconds since Jan 1. 1970 (the Unix Epoch) - so it is always
* expressed in GMT.
* *
* 2. the range is thus something about 580 million years, but due to current * 2. the range is thus something about 580 million years, but due to current
* algorithms limitations, only dates from Nov 24, 4714BC are handled * algorithms limitations, only dates from Nov 24, 4714BC are handled
@@ -33,6 +34,14 @@
* algorithm used by Scott E. Lee's code only works for positive JDNs, more * algorithm used by Scott E. Lee's code only works for positive JDNs, more
* or less) * or less)
* *
* 5. the object constructed for the given DD-MM-YYYY HH:MM:SS corresponds to
* this moment in local time and may be converted to the object
* corresponding to the same date/time in another time zone by using
* ToTimezone()
*
* 6. the conversions to the current (or any other) timezone are done when the
* internal time representation is converted to the broken-down one in
* wxDateTime::Tm.
*/ */
// ============================================================================ // ============================================================================
@@ -244,7 +253,8 @@ wxDateTime::Tm::Tm()
wday = wxDateTime::Inv_WeekDay; wday = wxDateTime::Inv_WeekDay;
} }
wxDateTime::Tm::Tm(const struct tm& tm) wxDateTime::Tm::Tm(const struct tm& tm, const TimeZone& tz)
: m_tz(tz)
{ {
msec = 0; msec = 0;
sec = tm.tm_sec; sec = tm.tm_sec;
@@ -321,7 +331,9 @@ wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz)
switch ( tz ) switch ( tz )
{ {
case wxDateTime::Local: case wxDateTime::Local:
// leave offset to be 0 // get the offset from C RTL: it returns the difference GMT-local
// while we want to have the offset _from_ GMT, hence the '-'
m_offset = -GetTimeZone();
break; break;
case wxDateTime::GMT_12: case wxDateTime::GMT_12:
@@ -336,7 +348,7 @@ wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz)
case wxDateTime::GMT_3: case wxDateTime::GMT_3:
case wxDateTime::GMT_2: case wxDateTime::GMT_2:
case wxDateTime::GMT_1: case wxDateTime::GMT_1:
m_offset = -60*(wxDateTime::GMT0 - tz); m_offset = -3600*(wxDateTime::GMT0 - tz);
break; break;
case wxDateTime::GMT0: case wxDateTime::GMT0:
@@ -352,12 +364,12 @@ wxDateTime::TimeZone::TimeZone(wxDateTime::TZ tz)
case wxDateTime::GMT10: case wxDateTime::GMT10:
case wxDateTime::GMT11: case wxDateTime::GMT11:
case wxDateTime::GMT12: case wxDateTime::GMT12:
m_offset = 60*(tz - wxDateTime::GMT0); m_offset = 3600*(tz - wxDateTime::GMT0);
break; break;
case wxDateTime::A_CST: case wxDateTime::A_CST:
// Central Standard Time in use in Australia = UTC + 9.5 // Central Standard Time in use in Australia = UTC + 9.5
m_offset = 9*60 + 30; m_offset = 60*(9*60 + 30);
break; break;
default: default:
@@ -533,30 +545,14 @@ wxString wxDateTime::GetWeekDayName(wxDateTime::WeekDay wday, bool abbr)
// constructors and assignment operators // constructors and assignment operators
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxDateTime& wxDateTime::Set(const struct tm& tm1) // the values in the tm structure contain the local time
wxDateTime& wxDateTime::Set(const struct tm& tm)
{ {
wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") ); wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
tm tm2(tm1); struct tm tm2(tm);
// we want the time in GMT, mktime() takes the local time, so use timegm()
// if it's available
#ifdef HAVE_TIMEGM
time_t timet = timegm(&tm2);
#else // !HAVE_TIMEGM
// FIXME this almost surely doesn't work
tm2.tm_sec -= GetTimeZone();
time_t timet = mktime(&tm2); time_t timet = mktime(&tm2);
if ( tm2.tm_isdst )
{
tm2.tm_hour += 1;
timet = mktime(&tm2);
}
#endif // HAVE_TIMEGM/!HAVE_TIMEGM
if ( timet == (time_t)(-1) ) if ( timet == (time_t)(-1) )
{ {
wxFAIL_MSG(_T("Invalid time")); wxFAIL_MSG(_T("Invalid time"));
@@ -584,7 +580,9 @@ wxDateTime& wxDateTime::Set(wxDateTime_t hour,
// get the current date from system // get the current date from system
time_t timet = GetTimeNow(); time_t timet = GetTimeNow();
struct tm *tm = gmtime(&timet); struct tm *tm = localtime(&timet);
wxCHECK_MSG( tm, ms_InvDateTime, _T("localtime() failed") );
// adjust the time // adjust the time
tm->tm_hour = hour; tm->tm_hour = hour;
@@ -634,7 +632,7 @@ wxDateTime& wxDateTime::Set(wxDateTime_t day,
tm.tm_hour = hour; tm.tm_hour = hour;
tm.tm_min = minute; tm.tm_min = minute;
tm.tm_sec = second; tm.tm_sec = second;
tm.tm_isdst = -1; // mktime() will guess it (wrongly, probably) tm.tm_isdst = -1; // mktime() will guess it
(void)Set(tm); (void)Set(tm);
@@ -651,7 +649,8 @@ wxDateTime& wxDateTime::Set(wxDateTime_t day,
m_time -= EPOCH_JDN; m_time -= EPOCH_JDN;
m_time *= SECONDS_PER_DAY * TIME_T_FACTOR; m_time *= SECONDS_PER_DAY * TIME_T_FACTOR;
Add(wxTimeSpan(hour, minute, second, millisec)); // JDN corresponds to GMT, we take localtime
Add(wxTimeSpan(hour, minute, second + GetTimeZone(), millisec));
} }
return *this; return *this;
@@ -673,7 +672,7 @@ wxDateTime& wxDateTime::Set(double jdn)
// time_t <-> broken down time conversions // time_t <-> broken down time conversions
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxDateTime::Tm wxDateTime::GetTm() const wxDateTime::Tm wxDateTime::GetTm(const TimeZone& tz) const
{ {
wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") ); wxASSERT_MSG( IsValid(), _T("invalid wxDateTime") );
@@ -681,24 +680,36 @@ wxDateTime::Tm wxDateTime::GetTm() const
if ( time != (time_t)-1 ) if ( time != (time_t)-1 )
{ {
// use C RTL functions // use C RTL functions
tm *tm = gmtime(&time); tm *tm;
if ( tz.GetOffset() == -GetTimeZone() )
{
// we are working with local time
tm = localtime(&time);
}
else
{
tm = gmtime(&time);
}
// should never happen // should never happen
wxCHECK_MSG( tm, Tm(), _T("gmtime() failed") ); wxCHECK_MSG( tm, Tm(), _T("gmtime() failed") );
return Tm(*tm); return Tm(*tm, tz);
} }
else else
{ {
// remember the time and do the calculations with the date only - this // remember the time and do the calculations with the date only - this
// eliminates rounding errors of the floating point arithmetics // eliminates rounding errors of the floating point arithmetics
wxLongLong timeMidnight = m_time; wxLongLong timeMidnight = m_time - GetTimeZone() * 1000;
long timeOnly = (m_time % MILLISECONDS_PER_DAY).ToLong(); long timeOnly = (timeMidnight % MILLISECONDS_PER_DAY).ToLong();
// we want to always have positive time and timeMidnight to be really
// the midnight before it
if ( timeOnly < 0 ) if ( timeOnly < 0 )
{ {
timeOnly = MILLISECONDS_PER_DAY - timeOnly; timeOnly = MILLISECONDS_PER_DAY + timeOnly;
} }
timeMidnight -= timeOnly; timeMidnight -= timeOnly;
@@ -950,7 +961,8 @@ bool wxDateTime::SetToWeekDay(WeekDay weekday,
double wxDateTime::GetJulianDayNumber() const double wxDateTime::GetJulianDayNumber() const
{ {
Tm tm(GetTm()); // JDN are always expressed for the GMT dates
Tm tm(ToTimezone(GMT0).GetTm(GMT0));
double result = GetTruncatedJDN(tm.mday, tm.mon, tm.year); double result = GetTruncatedJDN(tm.mday, tm.mon, tm.year);
@@ -968,31 +980,51 @@ double wxDateTime::GetRataDie() const
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// timezone stuff // timezone and DST stuff
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxDateTime& wxDateTime::MakeUTC() int wxDateTime::IsDST(wxDateTime::Country country) const
{ {
return Add(wxTimeSpan::Seconds(GetTimeZone())); wxCHECK_MSG( country == Country_Default, -1,
_T("country support not implemented") );
// use the C RTL for the dates in the standard range
time_t timet = GetTicks();
if ( timet != (time_t)-1 )
{
tm *tm = localtime(&timet);
wxCHECK_MSG( tm, -1, _T("localtime() failed") );
return tm->tm_isdst;
}
else
{
// wxFAIL_MSG( _T("TODO") );
return -1;
}
} }
wxDateTime& wxDateTime::MakeTimezone(const TimeZone& tz) wxDateTime& wxDateTime::MakeTimezone(const TimeZone& tz)
{ {
int minDiff = GetTimeZone() / SECONDS_IN_MINUTE + tz.GetOffset(); int secDiff = GetTimeZone() + tz.GetOffset();
return Add(wxTimeSpan::Minutes(minDiff));
// we need to know whether DST is or not in effect for this date
if ( IsDST() == 1 )
{
// FIXME we assume that the DST is always shifted by 1 hour
secDiff -= 3600;
} }
wxDateTime& wxDateTime::MakeLocalTime(const TimeZone& tz) return Substract(wxTimeSpan::Seconds(secDiff));
{
int minDiff = GetTimeZone() / SECONDS_IN_MINUTE + tz.GetOffset();
return Substract(wxTimeSpan::Minutes(minDiff));
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxDateTime to/from text representations // wxDateTime to/from text representations
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxString wxDateTime::Format(const wxChar *format) const wxString wxDateTime::Format(const wxChar *format, const TimeZone& tz) const
{ {
wxCHECK_MSG( format, _T(""), _T("NULL format in wxDateTime::Format") ); wxCHECK_MSG( format, _T(""), _T("NULL format in wxDateTime::Format") );
@@ -1000,7 +1032,18 @@ wxString wxDateTime::Format(const wxChar *format) const
if ( time != (time_t)-1 ) if ( time != (time_t)-1 )
{ {
// use strftime() // use strftime()
tm *tm = gmtime(&time); tm *tm;
if ( tz.GetOffset() == -GetTimeZone() )
{
// we are working with local time
tm = localtime(&time);
}
else
{
time += tz.GetOffset();
tm = gmtime(&time);
}
// should never happen // should never happen
wxCHECK_MSG( tm, _T(""), _T("gmtime() failed") ); wxCHECK_MSG( tm, _T(""), _T("gmtime() failed") );
@@ -1018,7 +1061,7 @@ wxString wxDateTime::Format(const wxChar *format) const
// the real year modulo 28 (so the week days coincide for them) // the real year modulo 28 (so the week days coincide for them)
// find the YEAR // find the YEAR
int yearReal = GetYear(); int yearReal = GetYear(tz);
int year = 1970 + yearReal % 28; int year = 1970 + yearReal % 28;
wxString strYear; wxString strYear;
@@ -1039,7 +1082,7 @@ wxString wxDateTime::Format(const wxChar *format) const
// use strftime() to format the same date but in supported year // use strftime() to format the same date but in supported year
wxDateTime dt(*this); wxDateTime dt(*this);
dt.SetYear(year); dt.SetYear(year);
wxString str = dt.Format(format); wxString str = dt.Format(format, tz);
// now replace the occurence of 1999 with the real year // now replace the occurence of 1999 with the real year
wxString strYearReal; wxString strYearReal;