QTimeZone - Define new class and api

Implement the new QTimeZone class based on the Olsen Time Zone ID's.

This is the base implementation and does not include the Platform
backends which are implemented separately.

This change does include a default UTC backed to be used if no Platform
backend is available, i.e. if QT_NO_SYSTEMLOCALE is set and ICU is not
configured.  This backend also provides a default set of time zones in
the standard "UTC+00:00" offset format that are guaranteed to always
exist regardless of the Platform backend.

This change includes conversion functions between the Olsen ID's and
Windows ID's using a conversion table based on Unicode CLDR data.
This is implemented for all platforms for scenarios such as a Linux
program needing to communicate with a Windows Exchange Server using
the Windows ID.

The CLDR conversion table is included under the UNICODE license, see
http://unicode.org/copyright.html for details.

[ChangeLog][QtCore][QTimeZone] Added new QTimeZone class to support
time tone calculations using the host platform time zone database
and the Olsen time zone ID's.

Change-Id: Ibb417d08cf2663a0979d2be855d2c6ad6ad01509
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
bb10
John Layt 2013-01-27 13:52:56 +00:00 committed by The Qt Project
parent ab55f9f39b
commit 48e2c3ac33
10 changed files with 3962 additions and 0 deletions

View File

@ -0,0 +1,899 @@
/****************************************************************************
**
** Copyright (C) 2013 John Layt <jlayt@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qtimezone.h"
#include "qtimezoneprivate_p.h"
#include <QtCore/qdatetime.h>
#include <qdebug.h>
QT_BEGIN_NAMESPACE
// Create default time zone using appropriate backend
static QTimeZonePrivate *newBackendTimeZone()
{
return new QUtcTimeZonePrivate();
}
// Create named time zone using appropriate backend
static QTimeZonePrivate *newBackendTimeZone(const QByteArray &olsenId)
{
return new QUtcTimeZonePrivate(olsenId);
}
class QTimeZoneSingleton
{
public:
QTimeZoneSingleton() : backend(newBackendTimeZone()) {}
// The backend_tz is the tz to use in static methods such as availableTimeZoneIds() and
// isTimeZoneIdAvailable() and to create named Olsen time zones. This is usually the host
// system, but may be different if the host resources are insufficient or if
// QT_NO_SYSTEMLOCALE is set. A simple UTC backend is used if no alternative is available.
QSharedDataPointer<QTimeZonePrivate> backend;
};
Q_GLOBAL_STATIC(QTimeZoneSingleton, global_tz);
/*!
\class QTimeZone
\inmodule QtCore
\since 5.2
\brief The QTimeZone class converts between between UTC and local time in a
specific time zone.
\threadsafe
This class provides a stateless calculator for time zone conversions
between UTC and the local time in a specific time zone. By default it uses
the host system time zone data to perform these conversions.
This class is primarily designed for use in QDateTime; most applications
will not need to access this class directly and should instead use
QDateTime with a Qt::TimeSpec of Qt::TimeZone.
\note For consistency with QDateTime, QTimeZone does not account for leap
seconds.
\section1
\section2 Olsen Time Zone IDs
QTimeZone uses the Olsen time zone IDs as defined in the IANA Time Zone
Database (http://www.iana.org/time-zones). This is to ensure a standard ID
across all supported platforms. Most platforms support the Olsen IDs
and the IANA Database natively, but for Windows a mapping is required to
the native IDs. See below for more details.
The Olsen IDs can and do change on a regular basis, and can vary depending
on how recently the host system data was updated. As such you cannot rely
on any given ID existing on any host system. You must use
availableTimeZoneIds() to determine what Olsen IDs are available.
\section2 UTC Offset Time Zones
A default UTC time zone backend is provided which is always guaranteed to
be available. This provides a set of generic Offset From UTC time zones
in the range UTC-14:00 to UTC+14:00. These time zones can be created
using either the standard ISO format names "UTC+00:00" as listed by
availableTimeZoneIds(), or using the number of offset seconds.
\section2 Windows Time Zones
Windows native time zone support is severely limited compared to the
standard IANA TZ Database. Windows time zones cover larger geographic
areas and are thus less accurate in their conversions. They also do not
support as much historic conversion data and so may only be accurate for
the current year.
QTimeZone uses a conversion table derived form the Unicode CLDR data to map
between Olsen IDs and Windows IDs. Depending on your version of Windows
and Qt, this table may not be able to provide a valid conversion, in which
"UTC" will be returned.
QTimeZone provides a public API to use this conversion table. The Windows ID
used is the Windows Registry Key for the time zone which is also the MS
Exchange EWS ID as well, but is different to the Time Zone Name (TZID) and
COD code used by MS Exchange in versions before 2007.
\section2 System Time Zone
QTimeZone does not support any concept of a system or default time zone.
If you require a QDateTime that uses the current system time zone at any
given moment then you should use a Qt::TimeSpec of Qt::LocalTime.
The method systemTimeZoneId() returns the current system Olsen time zone
ID which on OSX and Linux will always be correct. On Windows this ID is
translated from the the Windows system ID using an internal translation
table and the user's selected country. As a consequence there is a small
chance any Windows install may have IDs not known by Qt, in which case
"UTC" will be returned.
Creating a new QTimeZone instance using the system time zone ID will only
produce a fixed named copy of the time zone, it will not change if the
system time zone changes.
\section2 Time Zone Offsets
The difference between UTC and the local time in a time zone is expressed
as an offset in seconds from UTC, i.e. the number of seconds to add to UTC
to obtain the local time. The total offset is comprised of two component
parts, the standard time offset and the daylight time offset. The standard
time offset is the number of seconds to add to UTC to obtain standard time
in the time zone. The daylight time offset is the number of seconds to add
to the standard time offset to obtain daylight time in the time zone.
Note that the standard and daylight offsets for a time zone may change over
time as countries have changed daylight time laws or even their standard
time offset.
\section2 License
This class includes data obtained from the CLDR data files under the terms
of the Unicode license.
\legalese
COPYRIGHT AND PERMISSION NOTICE
Copyright © 1991-2012 Unicode, Inc. All rights reserved. Distributed under
the Terms of Use in http://www.unicode.org/copyright.html.
Permission is hereby granted, free of charge, to any person obtaining a
copy of the Unicode data files and any associated documentation (the "Data
Files") or Unicode software and any associated documentation (the "Software")
to deal in the Data Files or Software without restriction, including without
limitation the rights to use, copy, modify, merge, publish, distribute, and/or
sell copies of the Data Files or Software, and to permit persons to whom the
Data Files or Software are furnished to do so, provided that (a) the above
copyright notice(s) and this permission notice appear with all copies of the
Data Files or Software, (b) both the above copyright notice(s) and this
permission notice appear in associated documentation, and (c) there is clear
notice in each modified Data File or in the Software as well as in the
documentation associated with the Data File(s) or Software that the data or
software has been modified.
\endlegalese
\sa QDateTime
*/
/*!
\enum QTimeZone::TimeType
The type of time zone time, for example when requesting the name. In time
zones that do not apply daylight time, all three values may return the
same result.
\value StandardTime
The standard time in a time zone, i.e. when Daylight Savings is not
in effect.
For example when formatting a display name this will show something
like "Pacific Standard Time".
\value DaylightTime
A time when Daylight Savings is in effect.
For example when formatting a display name this will show something
like "Pacific daylight time".
\value GenericTime
A time which is not specifically Standard or Daylight time, either
an unknown time or a neutral form.
For example when formatting a display name this will show something
like "Pacific Time".
*/
/*!
\enum QTimeZone::NameType
The type of time zone name.
\value DefaultName
The default form of the time zone name, e.g. LongName, ShortName or OffsetName
\value LongName
The long form of the time zone name, e.g. "Central European Time"
\value ShortName
The short form of the time zone name, usually an abbreviation, e.g. "CET"
\value OffsetName
The standard ISO offset form of the time zone name, e.g. "UTC+01:00"
*/
/*!
\class QTimeZone::OffsetData
\inmodule QtCore
The time zone offset data for a given moment in time, i.e. the time zone
offsets and abbreviation to use at that moment in time.
\list
\li OffsetData::atUtc The datetime of the offset data in UTC time.
\li OffsetData::offsetFromUtc The total offset from UTC in effect at the datetime.
\li OffsetData::standardTimeOffset The standard time offset component of the total offset.
\li OffsetData::daylightTimeOffset The daylight time offset component of the total offset.
\li OffsetData::abbreviation The abbreviation in effect at the datetime.
\endlist
For example, for time zone "Europe/Berlin" the OffsetDate in standard and daylight time might be:
\list
\li atUtc = QDateTime(QDate(2013, 1, 1), QTime(0, 0, 0), Qt::UTC)
\li offsetFromUtc = 3600
\li standardTimeOffset = 3600
\li daylightTimeOffset = 0
\li abbreviation = "CET"
\endlist
\list
\li atUtc = QDateTime(QDate(2013, 6, 1), QTime(0, 0, 0), Qt::UTC)
\li offsetFromUtc = 7200
\li standardTimeOffset = 3600
\li daylightTimeOffset = 3600
\li abbreviation = "CEST"
\endlist
*/
/*!
\typedef QTimeZone::OffsetDataList
\relates QTimeZone
Synonym for QList<OffsetData>.
*/
/*!
Create a null/invalid time zone instance.
*/
QTimeZone::QTimeZone()
: d(0)
{
}
/*!
Creates an instance of the requested time zone \a olsenId.
The ID must be one of the available system IDs otherwise an invalid
time zone will be returned.
\sa availableTimeZoneIds()
*/
QTimeZone::QTimeZone(const QByteArray &olsenId)
{
// Try and see if it's a valid UTC offset ID, just as quick to try create as look-up
d = new QUtcTimeZonePrivate(olsenId);
// If not a valid UTC offset ID then try create it with the system backend
// Relies on backend not creating valid tz with invalid name
if (!d->isValid())
d = newBackendTimeZone(olsenId);
}
/*!
Creates an instance of a time zone with the requested Offset from UTC of
\a offsetSeconds.
The \a offsetSeconds from UTC must be in the range -14 hours to +14 hours
otherwise an invalid time zone will be returned.
*/
QTimeZone::QTimeZone(int offsetSeconds)
{
// offsetSeconds must fall between -14:00 and +14:00 hours
if (offsetSeconds >= -50400 && offsetSeconds <= 50400)
d = new QUtcTimeZonePrivate(offsetSeconds);
else
d = 0;
}
/*!
Creates a custom time zone with an ID of \a olsenId and an offset from UTC
of \a offsetSeconds. The \a name will be the name used by displayName()
for the LongName, the \a abbreviation will be used by displayName() for the
ShortName and by abbreviation(), and the optional \a country will be used
by country(). The \a comment is an optional note that may be displayed in
a GUI to assist users in selecting a time zone.
The \a olsenId must not be one of the available system IDs returned by
availableTimeZoneIds(). The \a offsetSeconds from UTC must be in the range
-14 hours to +14 hours.
If the custom time zone does not have a specific country then set it to the
default value of QLocale::AnyCountry.
*/
QTimeZone::QTimeZone(const QByteArray &olsenId, int offsetSeconds, const QString &name,
const QString &abbreviation, QLocale::Country country, const QString &comment)
{
// olsenId must be a valid ID and must not clash with the standard system names
if (QTimeZonePrivate::isValidId(olsenId) && !availableTimeZoneIds().contains(olsenId))
d = new QUtcTimeZonePrivate(olsenId, offsetSeconds, name, abbreviation, country, comment);
else
d = 0;
}
/*!
\internal
Private. Create time zone with given private backend
*/
QTimeZone::QTimeZone(QTimeZonePrivate &dd)
: d(&dd)
{
}
/*!
Copy constructor, copy \a other to this.
*/
QTimeZone::QTimeZone(const QTimeZone &other)
: d(other.d)
{
}
/*!
Destroys the time zone.
*/
QTimeZone::~QTimeZone()
{
}
/*!
Assignment operator, assign \a other to this.
*/
QTimeZone &QTimeZone::operator=(const QTimeZone &other)
{
d = other.d;
return *this;
}
/*!
Returns true if this time zone is equal to the \a other time zone.
*/
bool QTimeZone::operator==(const QTimeZone &other) const
{
if (d && other.d)
return (*d == *other.d);
else
return (d == other.d);
}
/*!
Returns true if this time zone is not equal to the \a other time zone.
*/
bool QTimeZone::operator!=(const QTimeZone &other) const
{
if (d && other.d)
return (*d != *other.d);
else
return (d != other.d);
}
/*!
Returns true if this time zone is valid.
*/
bool QTimeZone::isValid() const
{
if (d)
return d->isValid();
else
return false;
}
/*!
Returns the Olsen ID for the time zone.
Olsen IDs are used on all platforms. On Windows these are translated
from the Windows ID into the closest Olsen ID for the time zone and country.
*/
QByteArray QTimeZone::id() const
{
if (d)
return d->id();
else
return QByteArray();
}
/*!
Returns the country for the time zone.
*/
QLocale::Country QTimeZone::country() const
{
if (isValid())
return d->country();
else
return QLocale::AnyCountry;
}
/*!
Returns any comment for the time zone.
A comment may be provided by the host platform to assist users in
choosing the correct time zone. Depending on the platform this may not
be localized.
*/
QString QTimeZone::comment() const
{
if (isValid())
return d->comment();
else
return QString();
}
/*!
Returns the localized time zone display name at the given \a atDateTime
for the given \a nameType in the given \a locale. The \a nameType and
\a locale requested may not be supported on all platforms, in which case
the best available option will be returned.
If the \a locale is not provided then the application default locale will
be used.
The display name may change depending on daylight time or historical
events.
\sa abbreviation()
*/
QString QTimeZone::displayName(const QDateTime &atDateTime, NameType nameType,
const QLocale &locale) const
{
if (isValid())
return d->displayName(atDateTime.toMSecsSinceEpoch(), nameType, locale);
else
return QString();
}
/*!
Returns the localized time zone display name for the given \a timeType
and \a nameType in the given \a locale. The \a nameType and \a locale
requested may not be supported on all platforms, in which case the best
available option will be returned.
If the \a locale is not provided then the application default locale will
be used.
Where the time zone display names have changed over time then the most
recent names will be used.
\sa abbreviation()
*/
QString QTimeZone::displayName(TimeType timeType, NameType nameType,
const QLocale &locale) const
{
if (isValid())
return d->displayName(timeType, nameType, locale);
else
return QString();
}
/*!
Returns the time zone abbreviation at the given \a atDateTime. The
abbreviation may change depending on daylight time or even
historical events.
Note that the abbreviation is not guaranteed to be unique to this time zone
and should not be used in place of the ID or display name.
\sa displayName()
*/
QString QTimeZone::abbreviation(const QDateTime &atDateTime) const
{
if (isValid())
return d->abbreviation(atDateTime.toMSecsSinceEpoch());
else
return QString();
}
/*!
Returns the total effective offset at the given \a atDateTime, i.e. the
number of seconds to add to UTC to obtain the local time. This includes
any daylight time offset that may be in effect, i.e. it is the sum of
standardTimeOffset() and daylightTimeOffset() for the given datetime.
For example, for the time zone "Europe/Berlin" the standard time offset is
+3600 seconds and the daylight time offset is +3600 seconds. During standard
time offsetFromUtc() will return +3600 (UTC+01:00), and during daylight time
it will return +7200 (UTC+02:00).
\sa standardTimeOffset(), daylightTimeOffset()
*/
int QTimeZone::offsetFromUtc(const QDateTime &atDateTime) const
{
if (isValid())
return d->offsetFromUtc(atDateTime.toMSecsSinceEpoch());
else
return 0;
}
/*!
Returns the standard time offset at the given \a atDateTime, i.e. the
number of seconds to add to UTC to obtain the local Standard Time. This
excludes any daylight time offset that may be in effect.
For example, for the time zone "Europe/Berlin" the standard time offset is
+3600 seconds. During both standard and daylight time offsetFromUtc() will
return +3600 (UTC+01:00).
\sa offsetFromUtc(), daylightTimeOffset()
*/
int QTimeZone::standardTimeOffset(const QDateTime &atDateTime) const
{
if (isValid())
return d->standardTimeOffset(atDateTime.toMSecsSinceEpoch());
else
return 0;
}
/*!
Returns the daylight time offset at the given \a atDateTime, i.e. the
number of seconds to add to the standard time offset to obtain the local
daylight time.
For example, for the time zone "Europe/Berlin" the daylight time offset
is +3600 seconds. During standard time daylightTimeOffset() will return
0, and during daylight time it will return +3600.
\sa offsetFromUtc(), standardTimeOffset()
*/
int QTimeZone::daylightTimeOffset(const QDateTime &atDateTime) const
{
if (hasDaylightTime())
return d->daylightTimeOffset(atDateTime.toMSecsSinceEpoch());
else
return 0;
}
/*!
Returns true if the time zone has observed daylight time at any time.
\sa isDaylightTime(), daylightTimeOffset()
*/
bool QTimeZone::hasDaylightTime() const
{
if (isValid())
return d->hasDaylightTime();
else
return false;
}
/*!
Returns true if the given \a atDateTime is in daylight time.
\sa hasDaylightTime(), daylightTimeOffset()
*/
bool QTimeZone::isDaylightTime(const QDateTime &atDateTime) const
{
if (hasDaylightTime())
return d->isDaylightTime(atDateTime.toMSecsSinceEpoch());
else
return false;
}
/*!
Returns the effective offset details at the given \a forDateTime. This is
the equivalent of calling offsetFromUtc(), abbreviation(), etc individually but is
more efficient.
\sa offsetFromUtc(), standardTimeOffset(), daylightTimeOffset(), abbreviation()
*/
QTimeZone::OffsetData QTimeZone::offsetData(const QDateTime &forDateTime) const
{
if (hasTransitions())
return d->toOffsetData(d->data(forDateTime.toMSecsSinceEpoch()));
else
return d->invalidOffsetData();
}
/*!
Returns true if the system backend supports obtaining transitions.
*/
bool QTimeZone::hasTransitions() const
{
if (isValid())
return d->hasTransitions();
else
return false;
}
/*!
Returns the first time zone Transition after the given \a afterDateTime.
This is most useful when you have a Transition time and wish to find the
Transition after it.
The given \a afterDateTime is exclusive.
\sa hasTransitions(), previousTransition(), transitions()
*/
QTimeZone::OffsetData QTimeZone::nextTransition(const QDateTime &afterDateTime) const
{
if (hasTransitions())
return d->toOffsetData(d->nextTransition(afterDateTime.toMSecsSinceEpoch()));
else
return d->invalidOffsetData();
}
/*!
Returns the first time zone Transition before the given \a beforeDateTime.
This is most useful when you have a Transition time and wish to find the
Transition before it.
The given \a beforeDateTime is exclusive.
\sa hasTransitions(), nextTransition(), transitions()
*/
QTimeZone::OffsetData QTimeZone::previousTransition(const QDateTime &beforeDateTime) const
{
if (hasTransitions())
return d->toOffsetData(d->previousTransition(beforeDateTime.toMSecsSinceEpoch()));
else
return d->invalidOffsetData();
}
/*!
Returns a list of all time zone transitions between the given datetimes.
The given \a fromDateTime and \a toDateTime are inclusive.
\sa hasTransitions(), nextTransition(), previousTransition()
*/
QTimeZone::OffsetDataList QTimeZone::transitions(const QDateTime &fromDateTime,
const QDateTime &toDateTime) const
{
OffsetDataList list;
if (hasTransitions()) {
QTimeZonePrivate::DataList plist = d->transitions(fromDateTime.toMSecsSinceEpoch(),
toDateTime.toMSecsSinceEpoch());
foreach (const QTimeZonePrivate::Data &pdata, plist)
list.append(d->toOffsetData(pdata));
}
return list;
}
// Static methods
/*!
Returns the current system time zone Olsen ID.
On Windows this ID is translated from the the Windows ID using an internal
translation table and the user's selected country. As a consequence there
is a small chance any Windows install may have IDs not known by Qt, in
which case "UTC" will be returned.
*/
QByteArray QTimeZone::systemTimeZoneId()
{
return global_tz->backend->systemTimeZoneId();
}
/*!
Returns true if a given time zone \a olsenId is available on this system.
\sa availableTimeZoneIds()
*/
bool QTimeZone::isTimeZoneIdAvailable(const QByteArray &olsenId)
{
// isValidId is not strictly required, but faster to weed out invalid
// IDs as availableTimeZoneIds() may be slow
return (QTimeZonePrivate::isValidId(olsenId) && (availableTimeZoneIds().contains(olsenId)));
}
/*!
Returns a list of all available Olsen time zone IDs on this system.
\sa isTimeZoneIdAvailable()
*/
QList<QByteArray> QTimeZone::availableTimeZoneIds()
{
QSet<QByteArray> set = QUtcTimeZonePrivate().availableTimeZoneIds()
+ global_tz->backend->availableTimeZoneIds();
QList<QByteArray> list = set.toList();
qSort(list);
return list;
}
/*!
Returns a list of all available Olsen time zone IDs for a given \a country.
As a special case, a \a country of Qt::AnyCountry returns those time zones
that do not have any country related to them, such as UTC. If you require
a list of all time zone IDs for all countries then use the standard
availableTimeZoneIds() method.
\sa isTimeZoneIdAvailable()
*/
QList<QByteArray> QTimeZone::availableTimeZoneIds(QLocale::Country country)
{
QSet<QByteArray> set = QUtcTimeZonePrivate().availableTimeZoneIds(country)
+ global_tz->backend->availableTimeZoneIds(country);
QList<QByteArray> list = set.toList();
qSort(list);
return list;
}
/*!
Returns a list of all available Olsen time zone IDs with a given standard
time offset of \a offsetSeconds.
\sa isTimeZoneIdAvailable()
*/
QList<QByteArray> QTimeZone::availableTimeZoneIds(int offsetSeconds)
{
QSet<QByteArray> set = QUtcTimeZonePrivate().availableTimeZoneIds(offsetSeconds)
+ global_tz->backend->availableTimeZoneIds(offsetSeconds);
QList<QByteArray> list = set.toList();
qSort(list);
return list;
}
/*!
Returns the Windows ID equivalent to the given \a olsenId.
\sa windowsIdToDefaultOlsenId(), windowsIdToOlsenIds()
*/
QByteArray QTimeZone::olsenIdToWindowsId(const QByteArray &olsenId)
{
return QTimeZonePrivate::olsenIdToWindowsId(olsenId);
}
/*!
Returns the default Olsen ID for a given \a windowsId.
Because a Windows ID can cover several Olsen IDs in several different
countries, this function returns the most frequently used Olsen ID with no
regard for the country and should thus be used with care. It is usually
best to request the default for a specific country.
\sa olsenIdToWindowsId(), windowsIdToOlsenIds()
*/
QByteArray QTimeZone::windowsIdToDefaultOlsenId(const QByteArray &windowsId)
{
return QTimeZonePrivate::windowsIdToDefaultOlsenId(windowsId);
}
/*!
Returns the default Olsen ID for a given \a windowsId and \a country.
Because a Windows ID can cover several Olsen IDs within a given country,
the most frequently used Olsen ID in that country is returned.
As a special case, QLocale::AnyCountry returns the default of those Olsen IDs
that do not have any specific country.
\sa olsenIdToWindowsId(), windowsIdToOlsenIds()
*/
QByteArray QTimeZone::windowsIdToDefaultOlsenId(const QByteArray &windowsId,
QLocale::Country country)
{
return QTimeZonePrivate::windowsIdToDefaultOlsenId(windowsId, country);
}
/*!
Returns all the Olsen IDs for a given \a windowsId.
The returned list is sorted alphabetically.
\sa olsenIdToWindowsId(), windowsIdToDefaultOlsenId()
*/
QList<QByteArray> QTimeZone::windowsIdToOlsenIds(const QByteArray &windowsId)
{
return QTimeZonePrivate::windowsIdToOlsenIds(windowsId);
}
/*!
Returns all the Olsen IDs for a given \a windowsId and \a country.
As a special case QLocale::AnyCountry returns those Olsen IDs that do
not have any specific country.
The returned list is in order of frequency of usage, i.e. larger zones
within a country are listed first.
\sa olsenIdToWindowsId(), windowsIdToDefaultOlsenId()
*/
QList<QByteArray> QTimeZone::windowsIdToOlsenIds(const QByteArray &windowsId,
QLocale::Country country)
{
return QTimeZonePrivate::windowsIdToOlsenIds(windowsId, country);
}
#ifndef QT_NO_DATASTREAM
QDataStream &operator<<(QDataStream &ds, const QTimeZone &tz)
{
tz.d->serialize(ds);
return ds;
}
QDataStream &operator>>(QDataStream &ds, QTimeZone &tz)
{
QString olsenId;
ds >> olsenId;
if (olsenId == QStringLiteral("OffsetFromUtc")) {
int utcOffset;
QString name;
QString abbreviation;
int country;
QString comment;
ds >> olsenId >> utcOffset >> name >> abbreviation >> country >> comment;
tz = QTimeZone(olsenId.toUtf8(), utcOffset, name, abbreviation, (QLocale::Country) country, comment);
} else {
tz = QTimeZone(olsenId.toUtf8());
}
return ds;
}
#endif // QT_NO_DATASTREAM
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QTimeZone &tz)
{
//TODO Include backend and data version details?
dbg.nospace() << QStringLiteral("QTimeZone(") << qPrintable(QString::fromUtf8(tz.id())) << ')';
return dbg.space();
}
#endif
QT_END_NAMESPACE

View File

@ -0,0 +1,162 @@
/****************************************************************************
**
** Copyright (C) 2013 John Layt <jlayt@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QTIMEZONE_H
#define QTIMEZONE_H
#include <QtCore/qsharedpointer.h>
#include <QtCore/qlocale.h>
#include <QtCore/qdatetime.h>
QT_BEGIN_NAMESPACE
class QTimeZonePrivate;
class Q_CORE_EXPORT QTimeZone
{
public:
enum TimeType {
StandardTime = 0,
DaylightTime = 1,
GenericTime = 2
};
enum NameType {
DefaultName = 0,
LongName = 1,
ShortName = 2,
OffsetName = 3
};
struct OffsetData {
QString abbreviation;
QDateTime atUtc;
int offsetFromUtc;
int standardTimeOffset;
int daylightTimeOffset;
};
typedef QVector<OffsetData> OffsetDataList;
QTimeZone();
explicit QTimeZone(const QByteArray &olsenId);
QTimeZone(int offsetSeconds);
QTimeZone(const QByteArray &zoneId, int offsetSeconds, const QString &name,
const QString &abbreviation, QLocale::Country country = QLocale::AnyCountry,
const QString &comment = QString());
QTimeZone(const QTimeZone &other);
~QTimeZone();
QTimeZone &operator=(const QTimeZone &other);
#ifdef Q_COMPILER_RVALUE_REFS
QTimeZone &operator=(QTimeZone &&other) { std::swap(d, other.d); return *this; }
#endif
bool operator==(const QTimeZone &other) const;
bool operator!=(const QTimeZone &other) const;
bool isValid() const;
QByteArray id() const;
QLocale::Country country() const;
QString comment() const;
QString displayName(const QDateTime &atDateTime,
QTimeZone::NameType nameType = QTimeZone::DefaultName,
const QLocale &locale = QLocale()) const;
QString displayName(QTimeZone::TimeType timeType,
QTimeZone::NameType nameType = QTimeZone::DefaultName,
const QLocale &locale = QLocale()) const;
QString abbreviation(const QDateTime &atDateTime) const;
int offsetFromUtc(const QDateTime &atDateTime) const;
int standardTimeOffset(const QDateTime &atDateTime) const;
int daylightTimeOffset(const QDateTime &atDateTime) const;
bool hasDaylightTime() const;
bool isDaylightTime(const QDateTime &atDateTime) const;
OffsetData offsetData(const QDateTime &forDateTime) const;
bool hasTransitions() const;
OffsetData nextTransition(const QDateTime &afterDateTime) const;
OffsetData previousTransition(const QDateTime &beforeDateTime) const;
OffsetDataList transitions(const QDateTime &fromDateTime, const QDateTime &toDateTime) const;
static QByteArray systemTimeZoneId();
static bool isTimeZoneIdAvailable(const QByteArray &olsenId);
static QList<QByteArray> availableTimeZoneIds();
static QList<QByteArray> availableTimeZoneIds(QLocale::Country country);
static QList<QByteArray> availableTimeZoneIds(int offsetSeconds);
static QByteArray olsenIdToWindowsId(const QByteArray &olsenId);
static QByteArray windowsIdToDefaultOlsenId(const QByteArray &windowsId);
static QByteArray windowsIdToDefaultOlsenId(const QByteArray &windowsId,
QLocale::Country country);
static QList<QByteArray> windowsIdToOlsenIds(const QByteArray &windowsId);
static QList<QByteArray> windowsIdToOlsenIds(const QByteArray &windowsId,
QLocale::Country country);
private:
QTimeZone(QTimeZonePrivate &dd);
#ifndef QT_NO_DATASTREAM
friend Q_CORE_EXPORT QDataStream &operator<<(QDataStream &ds, const QTimeZone &tz);
#endif
friend class QTimeZonePrivate;
QSharedDataPointer<QTimeZonePrivate> d;
};
Q_DECLARE_TYPEINFO(QTimeZone::OffsetData, Q_MOVABLE_TYPE);
#ifndef QT_NO_DATASTREAM
Q_CORE_EXPORT QDataStream &operator<<(QDataStream &ds, const QTimeZone &tz);
Q_CORE_EXPORT QDataStream &operator>>(QDataStream &ds, QTimeZone &tz);
#endif
#ifndef QT_NO_DEBUG_STREAM
Q_CORE_EXPORT QDebug operator<<(QDebug dbg, const QTimeZone &tz);
#endif
QT_END_NAMESPACE
#endif // QTIMEZONE_H

View File

@ -0,0 +1,643 @@
/****************************************************************************
**
** Copyright (C) 2013 John Layt <jlayt@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qtimezone.h"
#include "qtimezoneprivate_p.h"
#include "qtimezoneprivate_data_p.h"
#include <qdebug.h>
QT_BEGIN_NAMESPACE
/*
Static utilities for looking up Windows ID tables
*/
static const int windowsDataTableSize = sizeof(windowsDataTable) / sizeof(QWindowsData) - 1;
static const int zoneDataTableSize = sizeof(zoneDataTable) / sizeof(QZoneData) - 1;
static const int utcDataTableSize = sizeof(utcDataTable) / sizeof(QUtcData) - 1;
static const QZoneData *zoneData(quint16 index)
{
Q_ASSERT(index < zoneDataTableSize);
return &zoneDataTable[index];
}
static const QWindowsData *windowsData(quint16 index)
{
Q_ASSERT(index < windowsDataTableSize);
return &windowsDataTable[index];
}
static const QUtcData *utcData(quint16 index)
{
Q_ASSERT(index < utcDataTableSize);
return &utcDataTable[index];
}
// Return the Windows ID literal for a given QWindowsData
static QByteArray windowsId(const QWindowsData *windowsData)
{
return (windowsIdData + windowsData->windowsIdIndex);
}
// Return the Olsen ID literal for a given QWindowsData
static QByteArray olsenId(const QWindowsData *windowsData)
{
return (olsenIdData + windowsData->olsenIdIndex);
}
// Return the Olsen ID literal for a given QZoneData
static QByteArray olsenId(const QZoneData *zoneData)
{
return (olsenIdData + zoneData->olsenIdIndex);
}
static QByteArray utcId(const QUtcData *utcData)
{
return (olsenIdData + utcData->olsenIdIndex);
}
static quint16 toWindowsIdKey(const QByteArray &winId)
{
for (quint16 i = 0; i < windowsDataTableSize; ++i) {
const QWindowsData *data = windowsData(i);
if (windowsId(data) == winId)
return data->windowsIdKey;
}
return 0;
}
static QByteArray toWindowsIdLiteral(quint16 windowsIdKey)
{
for (quint16 i = 0; i < windowsDataTableSize; ++i) {
const QWindowsData *data = windowsData(i);
if (data->windowsIdKey == windowsIdKey)
return windowsId(data);
}
return QByteArray();
}
/*
Base class implementing common utility routines, only intantiate for a null tz.
*/
QTimeZonePrivate::QTimeZonePrivate()
{
}
QTimeZonePrivate::QTimeZonePrivate(const QTimeZonePrivate &other)
: QSharedData(other), m_id(other.m_id)
{
}
QTimeZonePrivate::~QTimeZonePrivate()
{
}
QTimeZonePrivate *QTimeZonePrivate::clone()
{
return new QTimeZonePrivate(*this);
}
bool QTimeZonePrivate::operator==(const QTimeZonePrivate &other) const
{
// TODO Too simple, but need to solve problem of comparing different derived classes
// Should work for all System and ICU classes as names guaranteed unique, but not for Simple.
// Perhaps once all classes have working transitions can compare full list?
return (m_id == other.m_id);
}
bool QTimeZonePrivate::operator!=(const QTimeZonePrivate &other) const
{
return !(*this == other);
}
bool QTimeZonePrivate::isValid() const
{
return !m_id.isEmpty();
}
QByteArray QTimeZonePrivate::id() const
{
return m_id;
}
QLocale::Country QTimeZonePrivate::country() const
{
// Default fall-back mode, use the zoneTable to find Region of known Zones
for (int i = 0; i < zoneDataTableSize; ++i) {
const QZoneData *data = zoneData(i);
if (olsenId(data).split(' ').contains(m_id))
return (QLocale::Country)data->country;
}
return QLocale::AnyCountry;
}
QString QTimeZonePrivate::comment() const
{
return QString();
}
QString QTimeZonePrivate::displayName(qint64 atMSecsSinceEpoch,
QTimeZone::NameType nameType,
const QLocale &locale) const
{
if (nameType == QTimeZone::OffsetName)
return isoOffsetFormat(offsetFromUtc(atMSecsSinceEpoch));
if (isDaylightTime(atMSecsSinceEpoch))
return displayName(QTimeZone::DaylightTime, nameType, locale);
else
return displayName(QTimeZone::StandardTime, nameType, locale);
}
QString QTimeZonePrivate::displayName(QTimeZone::TimeType timeType,
QTimeZone::NameType nameType,
const QLocale &locale) const
{
Q_UNUSED(timeType)
Q_UNUSED(nameType)
Q_UNUSED(locale)
return QString();
}
QString QTimeZonePrivate::abbreviation(qint64 atMSecsSinceEpoch) const
{
Q_UNUSED(atMSecsSinceEpoch)
return QString();
}
int QTimeZonePrivate::offsetFromUtc(qint64 atMSecsSinceEpoch) const
{
return standardTimeOffset(atMSecsSinceEpoch) + daylightTimeOffset(atMSecsSinceEpoch);
}
int QTimeZonePrivate::standardTimeOffset(qint64 atMSecsSinceEpoch) const
{
Q_UNUSED(atMSecsSinceEpoch)
return invalidSeconds();
}
int QTimeZonePrivate::daylightTimeOffset(qint64 atMSecsSinceEpoch) const
{
Q_UNUSED(atMSecsSinceEpoch)
return invalidSeconds();
}
bool QTimeZonePrivate::hasDaylightTime() const
{
return false;
}
bool QTimeZonePrivate::isDaylightTime(qint64 atMSecsSinceEpoch) const
{
Q_UNUSED(atMSecsSinceEpoch)
return false;
}
QTimeZonePrivate::Data QTimeZonePrivate::data(qint64 forMSecsSinceEpoch) const
{
Q_UNUSED(forMSecsSinceEpoch)
return invalidData();
}
bool QTimeZonePrivate::hasTransitions() const
{
return false;
}
QTimeZonePrivate::Data QTimeZonePrivate::nextTransition(qint64 afterMSecsSinceEpoch) const
{
Q_UNUSED(afterMSecsSinceEpoch)
return invalidData();
}
QTimeZonePrivate::Data QTimeZonePrivate::previousTransition(qint64 beforeMSecsSinceEpoch) const
{
Q_UNUSED(beforeMSecsSinceEpoch)
return invalidData();
}
QTimeZonePrivate::DataList QTimeZonePrivate::transitions(qint64 fromMSecsSinceEpoch,
qint64 toMSecsSinceEpoch) const
{
DataList list;
if (toMSecsSinceEpoch > fromMSecsSinceEpoch) {
// fromMSecsSinceEpoch is inclusive but nextTransitionTime() is exclusive so go back 1 msec
Data next = nextTransition(fromMSecsSinceEpoch - 1);
while (next.atMSecsSinceEpoch <= toMSecsSinceEpoch) {
list.append(next);
next = nextTransition(next.atMSecsSinceEpoch);
}
}
return list;
}
QByteArray QTimeZonePrivate::systemTimeZoneId() const
{
return QByteArray();
}
QSet<QByteArray> QTimeZonePrivate::availableTimeZoneIds() const
{
return QSet<QByteArray>();
}
QSet<QByteArray> QTimeZonePrivate::availableTimeZoneIds(QLocale::Country country) const
{
// Default fall-back mode, use the zoneTable to find Region of know Zones
QSet<QByteArray> regionSet;
// First get all Zones in the Zones table belonging to the Region
for (int i = 0; i < zoneDataTableSize; ++i) {
if (zoneData(i)->country == country)
regionSet += olsenId(zoneData(i)).split(' ').toSet();
}
// Then select just those that are available
QSet<QByteArray> set;
foreach (const QByteArray &olsenId, availableTimeZoneIds()) {
if (regionSet.contains(olsenId))
set << olsenId;
}
return set;
}
QSet<QByteArray> QTimeZonePrivate::availableTimeZoneIds(int offsetFromUtc) const
{
// Default fall-back mode, use the zoneTable to find Offset of know Zones
QSet<QByteArray> offsetSet;
// First get all Zones in the table using the Offset
for (int i = 0; i < windowsDataTableSize; ++i) {
const QWindowsData *winData = windowsData(i);
if (winData->offsetFromUtc == offsetFromUtc) {
for (int j = 0; j < zoneDataTableSize; ++j) {
const QZoneData *data = zoneData(j);
if (data->windowsIdKey == winData->windowsIdKey)
offsetSet += olsenId(data).split(' ').toSet();
}
}
}
// Then select just those that are available
QSet<QByteArray> set;
foreach (const QByteArray &olsenId, availableTimeZoneIds()) {
if (offsetSet.contains(olsenId))
set << olsenId;
}
return set;
}
#ifndef QT_NO_DATASTREAM
void QTimeZonePrivate::serialize(QDataStream &ds) const
{
ds << QString::fromUtf8(m_id);
}
#endif // QT_NO_DATASTREAM
// Static Utility Methods
QTimeZonePrivate::Data QTimeZonePrivate::invalidData()
{
Data data;
data.atMSecsSinceEpoch = invalidMSecs();
data.offsetFromUtc = invalidSeconds();
data.standardTimeOffset = invalidSeconds();
data.daylightTimeOffset = invalidSeconds();
return data;
}
QTimeZone::OffsetData QTimeZonePrivate::invalidOffsetData()
{
QTimeZone::OffsetData offsetData;
offsetData.atUtc = QDateTime();
offsetData.offsetFromUtc = invalidSeconds();
offsetData.standardTimeOffset = invalidSeconds();
offsetData.daylightTimeOffset = invalidSeconds();
return offsetData;
}
QTimeZone::OffsetData QTimeZonePrivate::toOffsetData(const QTimeZonePrivate::Data &data)
{
QTimeZone::OffsetData offsetData = invalidOffsetData();
if (data.atMSecsSinceEpoch != invalidMSecs()) {
offsetData.atUtc = QDateTime::fromMSecsSinceEpoch(data.atMSecsSinceEpoch, Qt::UTC);
offsetData.offsetFromUtc = data.offsetFromUtc;
offsetData.standardTimeOffset = data.standardTimeOffset;
offsetData.daylightTimeOffset = data.daylightTimeOffset;
offsetData.abbreviation = data.abbreviation;
}
return offsetData;
}
// If the format of the ID is valid
bool QTimeZonePrivate::isValidId(const QByteArray &olsenId)
{
// Rules for defining TZ/Olsen names as per ftp://ftp.iana.org/tz/code/Theory
// * Use only valid POSIX file name components
// * Within a file name component, use only ASCII letters, `.', `-' and `_'.
// * Do not use digits
// * A file name component must not exceed 14 characters or start with `-'
// Aliases such as "Etc/GMT+7" and "SystemV/EST5EDT" are valid so we need to accept digits
if (olsenId.contains(' '))
return false;
QList<QByteArray> parts = olsenId.split('\\');
foreach (const QByteArray &part, parts) {
if (part.size() > 14)
return false;
if (part.at(0) == '-')
return false;
for (int i = 0; i < part.size(); ++i) {
QChar ch = part.at(i);
if (!(ch >= 'a' && ch <= 'z')
&& !(ch >= 'A' && ch <= 'Z')
&& !(ch == '_')
&& !(ch >= '0' && ch <= '9')
&& !(ch == '-')
&& !(ch == '.'))
return false;
}
}
return true;
}
QString QTimeZonePrivate::isoOffsetFormat(int offsetFromUtc)
{
const int mins = offsetFromUtc / 60;
return QString::fromUtf8("UTC%1%2:%3").arg(mins >= 0 ? QLatin1Char('+') : QLatin1Char('-'))
.arg(qAbs(mins) / 60, 2, 10, QLatin1Char('0'))
.arg(qAbs(mins) % 60, 2, 10, QLatin1Char('0'));
}
QByteArray QTimeZonePrivate::olsenIdToWindowsId(const QByteArray &id)
{
for (int i = 0; i < zoneDataTableSize; ++i) {
const QZoneData *data = zoneData(i);
if (olsenId(data).split(' ').contains(id))
return toWindowsIdLiteral(data->windowsIdKey);
}
return QByteArray();
}
QByteArray QTimeZonePrivate::windowsIdToDefaultOlsenId(const QByteArray &windowsId)
{
const quint16 windowsIdKey = toWindowsIdKey(windowsId);
for (int i = 0; i < windowsDataTableSize; ++i) {
const QWindowsData *data = windowsData(i);
if (data->windowsIdKey == windowsIdKey)
return olsenId(data);
}
return QByteArray();
}
QByteArray QTimeZonePrivate::windowsIdToDefaultOlsenId(const QByteArray &windowsId,
QLocale::Country country)
{
const QList<QByteArray> list = windowsIdToOlsenIds(windowsId, country);
if (list.count() > 0)
return list.first();
else
return QByteArray();
}
QList<QByteArray> QTimeZonePrivate::windowsIdToOlsenIds(const QByteArray &windowsId)
{
const quint16 windowsIdKey = toWindowsIdKey(windowsId);
QList<QByteArray> list;
for (int i = 0; i < zoneDataTableSize; ++i) {
const QZoneData *data = zoneData(i);
if (data->windowsIdKey == windowsIdKey)
list << olsenId(data).split(' ');
}
// Return the full list in alpha order
std::sort(list.begin(), list.end());
return list;
}
QList<QByteArray> QTimeZonePrivate::windowsIdToOlsenIds(const QByteArray &windowsId,
QLocale::Country country)
{
const quint16 windowsIdKey = toWindowsIdKey(windowsId);
for (int i = 0; i < zoneDataTableSize; ++i) {
const QZoneData *data = zoneData(i);
// Return the region matches in preference order
if (data->windowsIdKey == windowsIdKey && data->country == (quint16) country)
return olsenId(data).split(' ');
}
return QList<QByteArray>();
}
// Define template for derived classes to reimplement so QSharedDataPointer clone() works correctly
template<> QTimeZonePrivate *QSharedDataPointer<QTimeZonePrivate>::clone()
{
return d->clone();
}
/*
UTC Offset implementation, used when QT_NO_SYSTEMLOCALE set and QT_USE_ICU not set,
or for QDateTimes with a Qt:Spec of Qt::OffsetFromUtc.
*/
// Create default UTC time zone
QUtcTimeZonePrivate::QUtcTimeZonePrivate()
{
const QString name = QStringLiteral("UTC");
init(QByteArrayLiteral("UTC"), 0, name, name, QLocale::AnyCountry, name);
}
// Create a named UTC time zone
QUtcTimeZonePrivate::QUtcTimeZonePrivate(const QByteArray &id)
{
// Look for the name in the UTC list, if found set the values
for (int i = 0; i < utcDataTableSize; ++i) {
const QUtcData *data = utcData(i);
const QByteArray uid = utcId(data);
if (uid == id) {
QString name = QString::fromUtf8(id);
init(id, data->offsetFromUtc, name, name, QLocale::AnyCountry, name);
break;
}
}
}
// Create offset from UTC
QUtcTimeZonePrivate::QUtcTimeZonePrivate(qint32 offsetSeconds)
{
QString utcId;
if (offsetSeconds == 0)
utcId = QStringLiteral("UTC");
else
utcId = isoOffsetFormat(offsetSeconds);
init(utcId.toUtf8(), offsetSeconds, utcId, utcId, QLocale::AnyCountry, utcId);
}
QUtcTimeZonePrivate::QUtcTimeZonePrivate(const QByteArray &zoneId, int offsetSeconds,
const QString &name, const QString &abbreviation,
QLocale::Country country, const QString &comment)
{
init(zoneId, offsetSeconds, name, abbreviation, country, comment);
}
QUtcTimeZonePrivate::QUtcTimeZonePrivate(const QUtcTimeZonePrivate &other)
: QTimeZonePrivate(other), m_offsetFromUtc(other.m_offsetFromUtc), m_name(other.m_name),
m_abbreviation(other.m_abbreviation), m_country(other.m_country),
m_comment(other.m_comment)
{
}
QUtcTimeZonePrivate::~QUtcTimeZonePrivate()
{
}
QTimeZonePrivate *QUtcTimeZonePrivate::clone()
{
return new QUtcTimeZonePrivate(*this);
}
void QUtcTimeZonePrivate::init(const QByteArray &zoneId)
{
m_id = zoneId;
}
void QUtcTimeZonePrivate::init(const QByteArray &zoneId, int offsetSeconds, const QString &name,
const QString &abbreviation, QLocale::Country country,
const QString &comment)
{
m_id = zoneId;
m_offsetFromUtc = offsetSeconds;
m_name = name;
m_abbreviation = abbreviation;
m_country = country;
m_comment = comment;
}
QLocale::Country QUtcTimeZonePrivate::country() const
{
return m_country;
}
QString QUtcTimeZonePrivate::comment() const
{
return m_comment;
}
QString QUtcTimeZonePrivate::displayName(QTimeZone::TimeType timeType,
QTimeZone::NameType nameType,
const QLocale &locale) const
{
Q_UNUSED(timeType)
Q_UNUSED(locale)
if (nameType == QTimeZone::ShortName)
return m_abbreviation;
else if (nameType == QTimeZone::OffsetName)
return isoOffsetFormat(m_offsetFromUtc);
return m_name;
}
QString QUtcTimeZonePrivate::abbreviation(qint64 atMSecsSinceEpoch) const
{
Q_UNUSED(atMSecsSinceEpoch)
return m_abbreviation;
}
qint32 QUtcTimeZonePrivate::standardTimeOffset(qint64 atMSecsSinceEpoch) const
{
Q_UNUSED(atMSecsSinceEpoch)
return m_offsetFromUtc;
}
qint32 QUtcTimeZonePrivate::daylightTimeOffset(qint64 atMSecsSinceEpoch) const
{
Q_UNUSED(atMSecsSinceEpoch)
return 0;
}
QByteArray QUtcTimeZonePrivate::systemTimeZoneId() const
{
return QByteArrayLiteral("UTC");
}
QSet<QByteArray> QUtcTimeZonePrivate::availableTimeZoneIds() const
{
QSet<QByteArray> set;
for (int i = 0; i < utcDataTableSize; ++i)
set << utcId(utcData(i));
return set;
}
QSet<QByteArray> QUtcTimeZonePrivate::availableTimeZoneIds(QLocale::Country country) const
{
// If AnyCountry then is request for all non-region offset codes
if (country == QLocale::AnyCountry)
return availableTimeZoneIds();
return QSet<QByteArray>();
}
QSet<QByteArray> QUtcTimeZonePrivate::availableTimeZoneIds(qint32 offsetSeconds) const
{
QSet<QByteArray> set;
for (int i = 0; i < utcDataTableSize; ++i) {
const QUtcData *data = utcData(i);
if (data->offsetFromUtc == offsetSeconds)
set << utcId(data);
}
return set;
}
#ifndef QT_NO_DATASTREAM
void QUtcTimeZonePrivate::serialize(QDataStream &ds) const
{
ds << QStringLiteral("OffsetFromUtc") << QString::fromUtf8(m_id) << m_offsetFromUtc << m_name
<< m_abbreviation << (qint32) m_country << m_comment;
}
#endif // QT_NO_DATASTREAM
QT_END_NAMESPACE

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,198 @@
/****************************************************************************
**
** Copyright (C) 2013 John Layt <jlayt@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QTIMEZONEPRIVATE_P_H
#define QTIMEZONEPRIVATE_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists for the convenience
// of internal files. This header file may change from version to version
// without notice, or even be removed.
//
// We mean it.
//
#include "qtimezone.h"
#include "qlocale_p.h"
QT_BEGIN_NAMESPACE
class Q_CORE_EXPORT QTimeZonePrivate : public QSharedData
{
public:
//Version of QTimeZone::OffsetData struct using msecs for efficiency
struct Data {
QString abbreviation;
qint64 atMSecsSinceEpoch;
int offsetFromUtc;
int standardTimeOffset;
int daylightTimeOffset;
};
typedef QVector<Data> DataList;
// Create null time zone
QTimeZonePrivate();
QTimeZonePrivate(const QTimeZonePrivate &other);
virtual ~QTimeZonePrivate();
virtual QTimeZonePrivate *clone();
bool operator==(const QTimeZonePrivate &other) const;
bool operator!=(const QTimeZonePrivate &other) const;
bool isValid() const;
QByteArray id() const;
virtual QLocale::Country country() const;
virtual QString comment() const;
virtual QString displayName(qint64 atMSecsSinceEpoch,
QTimeZone::NameType nameType,
const QLocale &locale) const;
virtual QString displayName(QTimeZone::TimeType timeType,
QTimeZone::NameType nameType,
const QLocale &locale) const;
virtual QString abbreviation(qint64 atMSecsSinceEpoch) const;
virtual int offsetFromUtc(qint64 atMSecsSinceEpoch) const;
virtual int standardTimeOffset(qint64 atMSecsSinceEpoch) const;
virtual int daylightTimeOffset(qint64 atMSecsSinceEpoch) const;
virtual bool hasDaylightTime() const;
virtual bool isDaylightTime(qint64 atMSecsSinceEpoch) const;
virtual Data data(qint64 forMSecsSinceEpoch) const;
virtual bool hasTransitions() const;
virtual Data nextTransition(qint64 afterMSecsSinceEpoch) const;
virtual Data previousTransition(qint64 beforeMSecsSinceEpoch) const;
DataList transitions(qint64 fromMSecsSinceEpoch, qint64 toMSecsSinceEpoch) const;
virtual QByteArray systemTimeZoneId() const;
virtual QSet<QByteArray> availableTimeZoneIds() const;
virtual QSet<QByteArray> availableTimeZoneIds(QLocale::Country country) const;
virtual QSet<QByteArray> availableTimeZoneIds(int utcOffset) const;
virtual void serialize(QDataStream &ds) const;
// Static Utility Methods
static inline qint64 maxMSecs() { return std::numeric_limits<qint64>::max(); }
static inline qint64 minMSecs() { return std::numeric_limits<qint64>::min() + 1; }
static inline qint64 invalidMSecs() { return std::numeric_limits<qint64>::min(); }
static inline qint64 invalidSeconds() { return std::numeric_limits<int>::min(); }
static Data invalidData();
static QTimeZone::OffsetData invalidOffsetData();
static QTimeZone::OffsetData toOffsetData(const Data &data);
static bool isValidId(const QByteArray &olsenId);
static QString isoOffsetFormat(int offsetFromUtc);
static QByteArray olsenIdToWindowsId(const QByteArray &olsenId);
static QByteArray windowsIdToDefaultOlsenId(const QByteArray &windowsId);
static QByteArray windowsIdToDefaultOlsenId(const QByteArray &windowsId,
QLocale::Country country);
static QList<QByteArray> windowsIdToOlsenIds(const QByteArray &windowsId);
static QList<QByteArray> windowsIdToOlsenIds(const QByteArray &windowsId,
QLocale::Country country);
protected:
QByteArray m_id;
};
template<> QTimeZonePrivate *QSharedDataPointer<QTimeZonePrivate>::clone();
class Q_AUTOTEST_EXPORT QUtcTimeZonePrivate Q_DECL_FINAL : public QTimeZonePrivate
{
public:
// Create default UTC time zone
QUtcTimeZonePrivate();
// Create named time zone
QUtcTimeZonePrivate(const QByteArray &utcId);
// Create offset from UTC
QUtcTimeZonePrivate(int offsetSeconds);
// Create custom offset from UTC
QUtcTimeZonePrivate(const QByteArray &zoneId, int offsetSeconds, const QString &name,
const QString &abbreviation, QLocale::Country country,
const QString &comment);
QUtcTimeZonePrivate(const QUtcTimeZonePrivate &other);
virtual ~QUtcTimeZonePrivate();
QTimeZonePrivate *clone();
QLocale::Country country() const Q_DECL_OVERRIDE;
QString comment() const Q_DECL_OVERRIDE;
QString displayName(QTimeZone::TimeType timeType,
QTimeZone::NameType nameType,
const QLocale &locale) const Q_DECL_OVERRIDE;
QString abbreviation(qint64 atMSecsSinceEpoch) const Q_DECL_OVERRIDE;
int standardTimeOffset(qint64 atMSecsSinceEpoch) const Q_DECL_OVERRIDE;
int daylightTimeOffset(qint64 atMSecsSinceEpoch) const Q_DECL_OVERRIDE;
QByteArray systemTimeZoneId() const Q_DECL_OVERRIDE;
QSet<QByteArray> availableTimeZoneIds() const Q_DECL_OVERRIDE;
QSet<QByteArray> availableTimeZoneIds(QLocale::Country country) const Q_DECL_OVERRIDE;
QSet<QByteArray> availableTimeZoneIds(int utcOffset) const Q_DECL_OVERRIDE;
void serialize(QDataStream &ds) const Q_DECL_OVERRIDE;
private:
void init(const QByteArray &zoneId);
void init(const QByteArray &zoneId, int offsetSeconds, const QString &name,
const QString &abbreviation, QLocale::Country country,
const QString &comment);
int m_offsetFromUtc;
QString m_name;
QString m_abbreviation;
QLocale::Country m_country;
QString m_comment;
};
QT_END_NAMESPACE
#endif // QTIMEZONEPRIVATE_P_H

View File

@ -59,6 +59,9 @@ HEADERS += \
tools/qstringmatcher.h \
tools/qtextboundaryfinder.h \
tools/qtimeline.h \
tools/qtimezone.h \
tools/qtimezoneprivate_p.h \
tools/qtimezoneprivate_data_p.h \
tools/qelapsedtimer.h \
tools/qunicodetables_p.h \
tools/qunicodetools_p.h \
@ -104,6 +107,8 @@ SOURCES += \
tools/qstringlist.cpp \
tools/qtextboundaryfinder.cpp \
tools/qtimeline.cpp \
tools/qtimezone.cpp \
tools/qtimezoneprivate.cpp \
tools/qunicodetools.cpp \
tools/qvector.cpp \
tools/qvsnprintf.cpp

View File

@ -0,0 +1,8 @@
CONFIG += testcase parallel_test
TARGET = tst_qtimezone
QT += core-private testlib
SOURCES = tst_qtimezone.cpp
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
contains(QT_CONFIG,icu) {
DEFINES += QT_USE_ICU
}

View File

@ -0,0 +1,500 @@
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qtimezone.h>
#include <private/qtimezoneprivate_p.h>
#include <qlocale.h>
class tst_QTimeZone : public QObject
{
Q_OBJECT
public:
tst_QTimeZone();
private slots:
// Public class default system tests
void createTest();
void nullTest();
void dataStreamTest();
void availableTimeZoneIds();
void windowsId();
// Backend tests
void utcTest();
private:
void printTimeZone(const QTimeZone tz);
bool debug;
};
tst_QTimeZone::tst_QTimeZone()
{
// Set to true to print debug output
debug = false;
}
void tst_QTimeZone::printTimeZone(const QTimeZone tz)
{
QDateTime now = QDateTime::currentDateTime();
QDateTime jan = QDateTime(QDate(2012, 1, 1), QTime(0, 0, 0), Qt::UTC);
QDateTime jun = QDateTime(QDate(2012, 6, 1), QTime(0, 0, 0), Qt::UTC);
qDebug() << "";
qDebug() << "Time Zone = " << tz;
qDebug() << "";
qDebug() << "Is Valid = " << tz.isValid();
qDebug() << "";
qDebug() << "Zone ID = " << tz.id();
qDebug() << "Country = " << QLocale::countryToString(tz.country());
qDebug() << "Comment = " << tz.comment();
qDebug() << "";
qDebug() << "Locale = " << QLocale().name();
qDebug() << "Name Long = " << tz.displayName(QTimeZone::StandardTime, QTimeZone::LongName);
qDebug() << "Name Short = " << tz.displayName(QTimeZone::StandardTime, QTimeZone::ShortName);
qDebug() << "Name Offset = " << tz.displayName(QTimeZone::StandardTime, QTimeZone::OffsetName);
qDebug() << "Name Long DST = " << tz.displayName(QTimeZone::DaylightTime, QTimeZone::LongName);
qDebug() << "Name Short DST = " << tz.displayName(QTimeZone::DaylightTime, QTimeZone::ShortName);
qDebug() << "Name Offset DST = " << tz.displayName(QTimeZone::DaylightTime, QTimeZone::OffsetName);
qDebug() << "Name Long Generic = " << tz.displayName(QTimeZone::GenericTime, QTimeZone::LongName);
qDebug() << "Name Short Generic = " << tz.displayName(QTimeZone::GenericTime, QTimeZone::ShortName);
qDebug() << "Name Offset Generic = " << tz.displayName(QTimeZone::GenericTime, QTimeZone::OffsetName);
qDebug() << "";
QLocale locale = QLocale(QStringLiteral("de_DE"));
qDebug() << "Locale = " << locale.name();
qDebug() << "Name Long = " << tz.displayName(QTimeZone::StandardTime, QTimeZone::LongName, locale);
qDebug() << "Name Short = " << tz.displayName(QTimeZone::StandardTime, QTimeZone::ShortName, locale);
qDebug() << "Name Offset = " << tz.displayName(QTimeZone::StandardTime, QTimeZone::OffsetName, locale);
qDebug() << "Name Long DST = " << tz.displayName(QTimeZone::DaylightTime, QTimeZone::LongName,locale);
qDebug() << "Name Short DST = " << tz.displayName(QTimeZone::DaylightTime, QTimeZone::ShortName, locale);
qDebug() << "Name Offset DST = " << tz.displayName(QTimeZone::DaylightTime, QTimeZone::OffsetName, locale);
qDebug() << "Name Long Generic = " << tz.displayName(QTimeZone::GenericTime, QTimeZone::LongName, locale);
qDebug() << "Name Short Generic = " << tz.displayName(QTimeZone::GenericTime, QTimeZone::ShortName, locale);
qDebug() << "Name Offset Generic = " << tz.displayName(QTimeZone::GenericTime, QTimeZone::OffsetName, locale);
qDebug() << "";
qDebug() << "Abbreviation Now = " << tz.abbreviation(now);
qDebug() << "Abbreviation on 1 Jan = " << tz.abbreviation(jan);
qDebug() << "Abbreviation on 1 June = " << tz.abbreviation(jun);
qDebug() << "";
qDebug() << "Offset on 1 January = " << tz.offsetFromUtc(jan);
qDebug() << "Offset on 1 June = " << tz.offsetFromUtc(jun);
qDebug() << "Offset Now = " << tz.offsetFromUtc(now);
qDebug() << "";
qDebug() << "UTC Offset Now = " << tz.standardTimeOffset(now);
qDebug() << "UTC Offset on 1 January = " << tz.standardTimeOffset(jan);
qDebug() << "UTC Offset on 1 June = " << tz.standardTimeOffset(jun);
qDebug() << "";
qDebug() << "DST Offset on 1 January = " << tz.daylightTimeOffset(jan);
qDebug() << "DST Offset on 1 June = " << tz.daylightTimeOffset(jun);
qDebug() << "DST Offset Now = " << tz.daylightTimeOffset(now);
qDebug() << "";
qDebug() << "Has DST = " << tz.hasDaylightTime();
qDebug() << "Is DST Now = " << tz.isDaylightTime(now);
qDebug() << "Is DST on 1 January = " << tz.isDaylightTime(jan);
qDebug() << "Is DST on 1 June = " << tz.isDaylightTime(jun);
qDebug() << "";
qDebug() << "Has Transitions = " << tz.hasTransitions();
qDebug() << "Transition after 1 Jan = " << tz.nextTransition(jan).atUtc;
qDebug() << "Transition after 1 Jun = " << tz.nextTransition(jun).atUtc;
qDebug() << "Transition before 1 Jan = " << tz.previousTransition(jan).atUtc;
qDebug() << "Transition before 1 Jun = " << tz.previousTransition(jun).atUtc;
qDebug() << "";
}
void tst_QTimeZone::createTest()
{
QTimeZone tz("Pacific/Auckland");
if (debug)
printTimeZone(tz);
// If the tz is not valid then skip as is probably using the UTC backend which is tested later
if (!tz.isValid())
return;
// Validity tests
QCOMPARE(tz.isValid(), true);
// Comparison tests
QTimeZone tz2("Pacific/Auckland");
QTimeZone tz3("Australia/Sydney");
QCOMPARE((tz == tz2), true);
QCOMPARE((tz != tz2), false);
QCOMPARE((tz == tz3), false);
QCOMPARE((tz != tz3), true);
QCOMPARE(tz.country(), QLocale::NewZealand);
QDateTime jan = QDateTime(QDate(2012, 1, 1), QTime(0, 0, 0), Qt::UTC);
QDateTime jun = QDateTime(QDate(2012, 6, 1), QTime(0, 0, 0), Qt::UTC);
QDateTime janPrev = QDateTime(QDate(2011, 1, 1), QTime(0, 0, 0), Qt::UTC);
QCOMPARE(tz.offsetFromUtc(jan), 46800);
QCOMPARE(tz.offsetFromUtc(jun), 43200);
QCOMPARE(tz.standardTimeOffset(jan), 43200);
QCOMPARE(tz.standardTimeOffset(jun), 43200);
QCOMPARE(tz.daylightTimeOffset(jan), 3600);
QCOMPARE(tz.daylightTimeOffset(jun), 0);
QCOMPARE(tz.hasDaylightTime(), true);
QCOMPARE(tz.isDaylightTime(jan), true);
QCOMPARE(tz.isDaylightTime(jun), false);
// Only test transitions if host system supports them
if (tz.hasTransitions()) {
QTimeZone::OffsetData tran = tz.nextTransition(jan);
QCOMPARE(tran.atUtc.toMSecsSinceEpoch(), (qint64)1333202400000);
QCOMPARE(tran.offsetFromUtc, 43200);
QCOMPARE(tran.standardTimeOffset, 43200);
QCOMPARE(tran.daylightTimeOffset, 0);
tran = tz.nextTransition(jun);
QCOMPARE(tran.atUtc.toMSecsSinceEpoch(), (qint64)1348927200000);
QCOMPARE(tran.offsetFromUtc, 46800);
QCOMPARE(tran.standardTimeOffset, 43200);
QCOMPARE(tran.daylightTimeOffset, 3600);
tran = tz.previousTransition(jan);
QCOMPARE(tran.atUtc.toMSecsSinceEpoch(), (qint64)1316872800000);
QCOMPARE(tran.offsetFromUtc, 46800);
QCOMPARE(tran.standardTimeOffset, 43200);
QCOMPARE(tran.daylightTimeOffset, 3600);
tran = tz.previousTransition(jun);
QCOMPARE(tran.atUtc.toMSecsSinceEpoch(), (qint64)1333202400000);
QCOMPARE(tran.offsetFromUtc, 43200);
QCOMPARE(tran.standardTimeOffset, 43200);
QCOMPARE(tran.daylightTimeOffset, 0);
QTimeZone::OffsetDataList expected;
tran.atUtc = QDateTime::fromMSecsSinceEpoch(1301752800000, Qt::UTC);
tran.offsetFromUtc = 46800;
tran.standardTimeOffset = 43200;
tran.daylightTimeOffset = 3600;
expected << tran;
tran.atUtc = QDateTime::fromMSecsSinceEpoch(1316872800000, Qt::UTC);
tran.offsetFromUtc = 43200;
tran.standardTimeOffset = 43200;
tran.daylightTimeOffset = 0;
expected << tran;
QTimeZone::OffsetDataList result = tz.transitions(janPrev, jan);
QCOMPARE(result.count(), expected.count());
for (int i = 0; i > expected.count(); ++i) {
QCOMPARE(result.at(i).atUtc, expected.at(i).atUtc);
QCOMPARE(result.at(i).offsetFromUtc, expected.at(i).offsetFromUtc);
QCOMPARE(result.at(i).standardTimeOffset, expected.at(i).standardTimeOffset);
QCOMPARE(result.at(i).daylightTimeOffset, expected.at(i).daylightTimeOffset);
}
}
}
void tst_QTimeZone::nullTest()
{
QTimeZone nullTz1;
QTimeZone nullTz2;
QTimeZone utc("UTC");
// Validity tests
QCOMPARE(nullTz1.isValid(), false);
QCOMPARE(nullTz2.isValid(), false);
QCOMPARE(utc.isValid(), true);
// Comparison tests
QCOMPARE((nullTz1 == nullTz2), true);
QCOMPARE((nullTz1 != nullTz2), false);
QCOMPARE((nullTz1 == utc), false);
QCOMPARE((nullTz1 != utc), true);
// Assignment tests
nullTz2 = utc;
QCOMPARE(nullTz2.isValid(), true);
utc = nullTz1;
QCOMPARE(utc.isValid(), false);
QCOMPARE(nullTz1.id(), QByteArray());
QCOMPARE(nullTz1.country(), QLocale::AnyCountry);
QCOMPARE(nullTz1.comment(), QString());
QDateTime jan = QDateTime(QDate(2012, 1, 1), QTime(0, 0, 0), Qt::UTC);
QDateTime jun = QDateTime(QDate(2012, 6, 1), QTime(0, 0, 0), Qt::UTC);
QDateTime janPrev = QDateTime(QDate(2011, 1, 1), QTime(0, 0, 0), Qt::UTC);
QCOMPARE(nullTz1.abbreviation(jan), QString());
QCOMPARE(nullTz1.displayName(jan), QString());
QCOMPARE(nullTz1.displayName(QTimeZone::StandardTime), QString());
QCOMPARE(nullTz1.offsetFromUtc(jan), 0);
QCOMPARE(nullTz1.offsetFromUtc(jun), 0);
QCOMPARE(nullTz1.standardTimeOffset(jan), 0);
QCOMPARE(nullTz1.standardTimeOffset(jun), 0);
QCOMPARE(nullTz1.daylightTimeOffset(jan), 0);
QCOMPARE(nullTz1.daylightTimeOffset(jun), 0);
QCOMPARE(nullTz1.hasDaylightTime(), false);
QCOMPARE(nullTz1.isDaylightTime(jan), false);
QCOMPARE(nullTz1.isDaylightTime(jun), false);
QTimeZone::OffsetData data = nullTz1.offsetData(jan);
QCOMPARE(data.atUtc, QDateTime());
QCOMPARE(data.offsetFromUtc, std::numeric_limits<int>::min());
QCOMPARE(data.standardTimeOffset, std::numeric_limits<int>::min());
QCOMPARE(data.daylightTimeOffset, std::numeric_limits<int>::min());
QCOMPARE(nullTz1.hasTransitions(), false);
data = nullTz1.nextTransition(jan);
QCOMPARE(data.atUtc, QDateTime());
QCOMPARE(data.offsetFromUtc, std::numeric_limits<int>::min());
QCOMPARE(data.standardTimeOffset, std::numeric_limits<int>::min());
QCOMPARE(data.daylightTimeOffset, std::numeric_limits<int>::min());
data = nullTz1.previousTransition(jan);
QCOMPARE(data.atUtc, QDateTime());
QCOMPARE(data.offsetFromUtc, std::numeric_limits<int>::min());
QCOMPARE(data.standardTimeOffset, std::numeric_limits<int>::min());
QCOMPARE(data.daylightTimeOffset, std::numeric_limits<int>::min());
}
void tst_QTimeZone::dataStreamTest()
{
// Test the OffsetFromUtc backend serialization
QTimeZone tz1("QST", 123456, "Qt Standard Time", "QST", QLocale::Norway, "Qt Testing");
QByteArray tmp;
{
QDataStream ds(&tmp, QIODevice::WriteOnly);
ds << tz1;
}
QTimeZone tz2("UTC");
{
QDataStream ds(&tmp, QIODevice::ReadOnly);
ds >> tz2;
}
QCOMPARE(tz2.id(), QByteArray("QST"));
QCOMPARE(tz2.comment(), QString("Qt Testing"));
QCOMPARE(tz2.country(), QLocale::Norway);
QCOMPARE(tz2.abbreviation(QDateTime::currentDateTime()), QString("QST"));
QCOMPARE(tz2.displayName(QTimeZone::StandardTime, QTimeZone::LongName, QString()),
QString("Qt Standard Time"));
QCOMPARE(tz2.displayName(QTimeZone::DaylightTime, QTimeZone::LongName, QString()),
QString("Qt Standard Time"));
QCOMPARE(tz2.offsetFromUtc(QDateTime::currentDateTime()), 123456);
// Test the system backend serialization
tz1 = QTimeZone("Pacific/Auckland");
// If not valid then probably using the UTC system backend so skip
if (!tz1.isValid())
return;
{
QDataStream ds(&tmp, QIODevice::WriteOnly);
ds << tz1;
}
tz2 = QTimeZone("UTC");
{
QDataStream ds(&tmp, QIODevice::ReadOnly);
ds >> tz2;
}
QCOMPARE(tz2.id(), tz1.id());
}
void tst_QTimeZone::availableTimeZoneIds()
{
if (debug) {
qDebug() << "";
qDebug() << "Available Time Zones" ;
qDebug() << QTimeZone::availableTimeZoneIds();
qDebug() << "";
qDebug() << "Available Time Zones in the US";
qDebug() << QTimeZone::availableTimeZoneIds(QLocale::UnitedStates);
qDebug() << "";
qDebug() << "Available Time Zones with UTC Offset 0";
qDebug() << QTimeZone::availableTimeZoneIds(0);
qDebug() << "";
} else {
//Just test the calls work, we cannot know what any test machine has available
QList<QByteArray> listAll = QTimeZone::availableTimeZoneIds();
QList<QByteArray> listUs = QTimeZone::availableTimeZoneIds(QLocale::UnitedStates);
QList<QByteArray> listZero = QTimeZone::availableTimeZoneIds(0);
}
}
void tst_QTimeZone::windowsId()
{
/*
Current Windows zones for "Central Standard Time":
Region Olsen Id(s)
Default "America/Chicago"
Canada "America/Winnipeg America/Rainy_River America/Rankin_Inlet America/Resolute"
Mexico "America/Matamoros"
USA "America/Chicago America/Indiana/Knox America/Indiana/Tell_City America/Menominee"
"America/North_Dakota/Beulah America/North_Dakota/Center"
"America/North_Dakota/New_Salem"
AnyCountry "CST6CDT"
*/
QCOMPARE(QTimeZone::olsenIdToWindowsId("America/Chicago"),
QByteArray("Central Standard Time"));
QCOMPARE(QTimeZone::olsenIdToWindowsId("America/Resolute"),
QByteArray("Central Standard Time"));
// Partials shouldn't match
QCOMPARE(QTimeZone::olsenIdToWindowsId("America/Chi"), QByteArray());
QCOMPARE(QTimeZone::olsenIdToWindowsId("InvalidZone"), QByteArray());
QCOMPARE(QTimeZone::olsenIdToWindowsId(QByteArray()), QByteArray());
// Check default value
QCOMPARE(QTimeZone::windowsIdToDefaultOlsenId("Central Standard Time"),
QByteArray("America/Chicago"));
QCOMPARE(QTimeZone::windowsIdToDefaultOlsenId("Central Standard Time", QLocale::Canada),
QByteArray("America/Winnipeg"));
QCOMPARE(QTimeZone::windowsIdToDefaultOlsenId("Central Standard Time", QLocale::AnyCountry),
QByteArray("CST6CDT"));
QCOMPARE(QTimeZone::windowsIdToDefaultOlsenId(QByteArray()), QByteArray());
// No country is sorted list of all zones
QList<QByteArray> list;
list << "America/Chicago" << "America/Indiana/Knox" << "America/Indiana/Tell_City"
<< "America/Matamoros" << "America/Menominee" << "America/North_Dakota/Beulah"
<< "America/North_Dakota/Center" << "America/North_Dakota/New_Salem"
<< "America/Rainy_River" << "America/Rankin_Inlet" << "America/Resolute"
<< "America/Winnipeg" << "CST6CDT";
QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time"), list);
// Check country with no match returns empty list
list.clear();
QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time", QLocale::NewZealand),
list);
// Check valid country returns list in preference order
list.clear();
list << "America/Winnipeg" << "America/Rainy_River" << "America/Rankin_Inlet"
<< "America/Resolute";
QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time", QLocale::Canada), list);
list.clear();
list << "America/Matamoros";
QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time", QLocale::Mexico), list);
list.clear();
list << "America/Chicago" << "America/Indiana/Knox" << "America/Indiana/Tell_City"
<< "America/Menominee" << "America/North_Dakota/Beulah" << "America/North_Dakota/Center"
<< "America/North_Dakota/New_Salem";
QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time", QLocale::UnitedStates),
list);
list.clear();
list << "CST6CDT";
QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time", QLocale::AnyCountry),
list);
// Check no windowsId return empty
list.clear();
QCOMPARE(QTimeZone::windowsIdToOlsenIds(QByteArray()), list);
QCOMPARE(QTimeZone::windowsIdToOlsenIds(QByteArray(), QLocale::AnyCountry), list);
}
void tst_QTimeZone::utcTest()
{
#ifdef QT_BUILD_INTERNAL
// Test default UTC constructor
QUtcTimeZonePrivate tzp;
QCOMPARE(tzp.isValid(), true);
QCOMPARE(tzp.id(), QByteArray("UTC"));
QCOMPARE(tzp.country(), QLocale::AnyCountry);
QCOMPARE(tzp.abbreviation(0), QString("UTC"));
QCOMPARE(tzp.displayName(QTimeZone::StandardTime, QTimeZone::LongName, QString()), QString("UTC"));
QCOMPARE(tzp.offsetFromUtc(0), 0);
QCOMPARE(tzp.standardTimeOffset(0), 0);
QCOMPARE(tzp.daylightTimeOffset(0), 0);
QCOMPARE(tzp.hasDaylightTime(), false);
QCOMPARE(tzp.hasTransitions(), false);
// Test create from UTC Offset
QDateTime now = QDateTime::currentDateTime();
QTimeZone tz(36000);
QCOMPARE(tz.isValid(), true);
QCOMPARE(tz.id(), QByteArray("UTC+10:00"));
QCOMPARE(tz.offsetFromUtc(now), 36000);
QCOMPARE(tz.standardTimeOffset(now), 36000);
QCOMPARE(tz.daylightTimeOffset(now), 0);
// Test invalid UTC offset, must be in range -14 to +14 hours
int min = -14*60*60;
int max = 14*60*60;
QCOMPARE(QTimeZone(min - 1).isValid(), false);
QCOMPARE(QTimeZone(min).isValid(), true);
QCOMPARE(QTimeZone(min + 1).isValid(), true);
QCOMPARE(QTimeZone(max - 1).isValid(), true);
QCOMPARE(QTimeZone(max).isValid(), true);
QCOMPARE(QTimeZone(max + 1).isValid(), false);
// Test create from standard name
tz = QTimeZone("UTC+10:00");
QCOMPARE(tz.isValid(), true);
QCOMPARE(tz.id(), QByteArray("UTC+10:00"));
QCOMPARE(tz.offsetFromUtc(now), 36000);
QCOMPARE(tz.standardTimeOffset(now), 36000);
QCOMPARE(tz.daylightTimeOffset(now), 0);
// Test invalid UTC ID, must be in available list
tz = QTimeZone("UTC+00:01");
QCOMPARE(tz.isValid(), false);
// Test create custom zone
tz = QTimeZone("QST", 123456, "Qt Standard Time", "QST", QLocale::Norway, "Qt Testing");
QCOMPARE(tz.isValid(), true);
QCOMPARE(tz.id(), QByteArray("QST"));
QCOMPARE(tz.comment(), QString("Qt Testing"));
QCOMPARE(tz.country(), QLocale::Norway);
QCOMPARE(tz.abbreviation(now), QString("QST"));
QCOMPARE(tz.displayName(QTimeZone::StandardTime, QTimeZone::LongName, QString()),
QString("Qt Standard Time"));
QCOMPARE(tz.offsetFromUtc(now), 123456);
QCOMPARE(tz.standardTimeOffset(now), 123456);
QCOMPARE(tz.daylightTimeOffset(now), 0);
#endif // QT_BUILD_INTERNAL
}
QTEST_APPLESS_MAIN(tst_QTimeZone)
#include "tst_qtimezone.moc"

View File

@ -48,6 +48,7 @@ SUBDIRS=\
qstringref \
qtextboundaryfinder \
qtime \
qtimezone \
qtimeline \
qvarlengtharray \
qvector

View File

@ -0,0 +1,424 @@
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
## Contact: http://www.qt-project.org/legal
##
## This file is part of the test suite of the Qt Toolkit.
##
## $QT_BEGIN_LICENSE:LGPL$
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and Digia. For licensing terms and
## conditions see http://qt.digia.com/licensing. For further information
## use the contact form at http://qt.digia.com/contact-us.
##
## GNU Lesser General Public License Usage
## Alternatively, this file may be used under the terms of the GNU Lesser
## General Public License version 2.1 as published by the Free Software
## Foundation and appearing in the file LICENSE.LGPL included in the
## packaging of this file. Please review the following information to
## ensure the GNU Lesser General Public License version 2.1 requirements
## will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
##
## In addition, as a special exception, Digia gives you certain additional
## rights. These rights are described in the Digia Qt LGPL Exception
## version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
##
## GNU General Public License Usage
## Alternatively, this file may be used under the terms of the GNU
## General Public License version 3.0 as published by the Free Software
## Foundation and appearing in the file LICENSE.GPL included in the
## packaging of this file. Please review the following information to
## ensure the GNU General Public License version 3.0 requirements will be
## met: http://www.gnu.org/copyleft/gpl.html.
##
##
## $QT_END_LICENSE$
##
#############################################################################
# Script to parse the CLDR supplemental/windowsZones.xml file and encode for use in QTimeZone
# XML structure is as follows:
#
# <supplementalData>
# <version number="$Revision: 7825 $"/>
# <generation date="$Date: 2012-10-10 14:45:31 -0700 (Wed, 10 Oct 2012) $"/>
# <windowsZones>
# <mapTimezones otherVersion="7dc0101" typeVersion="2012f">
# <!-- (UTC-08:00) Pacific Time (US & Canada) -->
# <mapZone other="Pacific Standard Time" territory="001" type="America/Los_Angeles"/>
# <mapZone other="Pacific Standard Time" territory="CA" type="America/Vancouver America/Dawson America/Whitehorse"/>
# <mapZone other="Pacific Standard Time" territory="MX" type="America/Tijuana"/>
# <mapZone other="Pacific Standard Time" territory="US" type="America/Los_Angeles"/>
# <mapZone other="Pacific Standard Time" territory="ZZ" type="PST8PDT"/>
# </mapTimezones>
# </windowsZones>
# </supplementalData>
import os
import sys
import datetime
import tempfile
import enumdata
import xpathlite
from xpathlite import DraftResolution
import re
import qlocalexml2cpp
findAlias = xpathlite.findAlias
findEntry = xpathlite.findEntry
findEntryInFile = xpathlite._findEntryInFile
findTagsInFile = xpathlite.findTagsInFile
unicode2hex = qlocalexml2cpp.unicode2hex
wrap_list = qlocalexml2cpp.wrap_list
class ByteArrayData:
def __init__(self):
self.data = []
self.hash = {}
def append(self, s):
s = s + '\0'
if s in self.hash:
return self.hash[s]
lst = unicode2hex(s)
index = len(self.data)
if index > 65535:
print "\n\n\n#error Data index is too big!"
sys.stderr.write ("\n\n\nERROR: index exceeds the uint16 range! index = %d\n" % index)
sys.exit(1)
self.hash[s] = index
self.data += lst
return index
# List of currently known Windows IDs. If script fails on missing ID plase add it here
# Not public so may be safely changed.
# Windows Key : [ Windows Id, Offset Seconds ]
windowsIdList = {
1 : [ u'Afghanistan Standard Time', 16200 ],
2 : [ u'Alaskan Standard Time', -32400 ],
3 : [ u'Arab Standard Time', 10800 ],
4 : [ u'Arabian Standard Time', 14400 ],
5 : [ u'Arabic Standard Time', 10800 ],
6 : [ u'Argentina Standard Time', 10800 ],
7 : [ u'Atlantic Standard Time', -14400 ],
8 : [ u'AUS Central Standard Time', 34200 ],
9 : [ u'AUS Eastern Standard Time', 36000 ],
10 : [ u'Azerbaijan Standard Time', 14400 ],
11 : [ u'Azores Standard Time', -3600 ],
12 : [ u'Bahia Standard Time', 10800 ],
13 : [ u'Bangladesh Standard Time', 21600 ],
14 : [ u'Canada Central Standard Time', -21600 ],
15 : [ u'Cape Verde Standard Time', -3600 ],
16 : [ u'Caucasus Standard Time', 14400 ],
17 : [ u'Cen. Australia Standard Time', 34200 ],
18 : [ u'Central America Standard Time', -21600 ],
19 : [ u'Central Asia Standard Time', 21600 ],
20 : [ u'Central Brazilian Standard Time', -14400 ],
21 : [ u'Central Europe Standard Time', 3600 ],
22 : [ u'Central European Standard Time', 3600 ],
23 : [ u'Central Pacific Standard Time', 39600 ],
24 : [ u'Central Standard Time (Mexico)', -21600 ],
25 : [ u'Central Standard Time', -21600 ],
26 : [ u'China Standard Time', 28800 ],
27 : [ u'Dateline Standard Time', -43200 ],
28 : [ u'E. Africa Standard Time', 10800 ],
29 : [ u'E. Australia Standard Time', 36000 ],
30 : [ u'E. Europe Standard Time', 7200 ],
31 : [ u'E. South America Standard Time', -10800 ],
32 : [ u'Eastern Standard Time', -18000 ],
33 : [ u'Egypt Standard Time', 7200 ],
34 : [ u'Ekaterinburg Standard Time', 21600 ],
35 : [ u'Fiji Standard Time', 43200 ],
36 : [ u'FLE Standard Time', 7200 ],
37 : [ u'Georgian Standard Time', 14400 ],
38 : [ u'GMT Standard Time', 0 ],
39 : [ u'Greenland Standard Time', 10800 ],
40 : [ u'Greenwich Standard Time', 0 ],
41 : [ u'GTB Standard Time', 7200 ],
42 : [ u'Hawaiian Standard Time', -36000 ],
43 : [ u'India Standard Time', 19800 ],
44 : [ u'Iran Standard Time', 12600 ],
45 : [ u'Israel Standard Time', 7200 ],
46 : [ u'Jordan Standard Time', 7200 ],
47 : [ u'Kaliningrad Standard Time', 10800 ],
48 : [ u'Korea Standard Time', 32400 ],
49 : [ u'Magadan Standard Time', 43200 ],
50 : [ u'Mauritius Standard Time', 14400 ],
51 : [ u'Middle East Standard Time', 7200 ],
52 : [ u'Montevideo Standard Time', 10800 ],
53 : [ u'Morocco Standard Time', 0 ],
54 : [ u'Mountain Standard Time (Mexico)', -25200 ],
55 : [ u'Mountain Standard Time', -25200 ],
56 : [ u'Myanmar Standard Time', 23400 ],
57 : [ u'N. Central Asia Standard Time', 23400 ],
58 : [ u'Namibia Standard Time', 3600 ],
59 : [ u'Nepal Standard Time', 20700 ],
60 : [ u'New Zealand Standard Time', 43200 ],
61 : [ u'Newfoundland Standard Time', -12600 ],
62 : [ u'North Asia East Standard Time', 32400 ],
63 : [ u'North Asia Standard Time', 28800 ],
64 : [ u'Pacific SA Standard Time', -14400 ],
65 : [ u'Pacific Standard Time (Mexico)', -28800 ],
66 : [ u'Pacific Standard Time', -28800 ],
67 : [ u'Pakistan Standard Time', 18000 ],
68 : [ u'Paraguay Standard Time', -14400 ],
69 : [ u'Romance Standard Time', 3600 ],
70 : [ u'Russian Standard Time', 14400 ],
71 : [ u'SA Eastern Standard Time', 10800 ],
72 : [ u'SA Pacific Standard Time', -18000 ],
73 : [ u'SA Western Standard Time', -14400 ],
74 : [ u'Samoa Standard Time', 46800 ],
75 : [ u'SE Asia Standard Time', 23400 ],
76 : [ u'Singapore Standard Time', 28800 ],
77 : [ u'South Africa Standard Time', 7200 ],
78 : [ u'Sri Lanka Standard Time', 19800 ],
79 : [ u'Syria Standard Time', 7200 ],
80 : [ u'Taipei Standard Time', 28800 ],
81 : [ u'Tasmania Standard Time', 36000 ],
82 : [ u'Tokyo Standard Time', 32400 ],
83 : [ u'Tonga Standard Time', 46800 ],
84 : [ u'Turkey Standard Time', 7200 ],
85 : [ u'Ulaanbaatar Standard Time', 28800 ],
86 : [ u'US Eastern Standard Time', -18000 ],
87 : [ u'US Mountain Standard Time', -25200 ],
88 : [ u'UTC-02', -7200 ],
89 : [ u'UTC-11', -39600 ],
90 : [ u'UTC', 0 ],
91 : [ u'UTC+12', 43200 ],
92 : [ u'Venezuela Standard Time', -16200 ],
93 : [ u'Vladivostok Standard Time', 39600 ],
94 : [ u'W. Australia Standard Time', 28800 ],
95 : [ u'W. Central Africa Standard Time', 3600 ],
96 : [ u'W. Europe Standard Time', 3600 ],
97 : [ u'West Asia Standard Time', 18000 ],
98 : [ u'West Pacific Standard Time', 36000 ],
99 : [ u'Yakutsk Standard Time', 36000 ]
}
def windowsIdToKey(windowsId):
for windowsKey in windowsIdList:
if windowsIdList[windowsKey][0] == windowsId:
return windowsKey
return 0
# List of standard UTC IDs to use. Not public so may be safely changed.
# Do not remove ID's as is part of API/behavior guarantee
# Key : [ UTC Id, Offset Seconds ]
utcIdList = {
0 : [ u'UTC', 0 ], # Goes first so is default
1 : [ u'UTC-14:00', -50400 ],
2 : [ u'UTC-13:00', -46800 ],
3 : [ u'UTC-12:00', -43200 ],
4 : [ u'UTC-11:00', -39600 ],
5 : [ u'UTC-10:00', -36000 ],
6 : [ u'UTC-09:00', -32400 ],
7 : [ u'UTC-08:00', -28800 ],
8 : [ u'UTC-07:00', -25200 ],
9 : [ u'UTC-06:00', -21600 ],
10 : [ u'UTC-05:00', -18000 ],
11 : [ u'UTC-04:30', -16200 ],
12 : [ u'UTC-04:00', -14400 ],
13 : [ u'UTC-03:30', -12600 ],
14 : [ u'UTC-03:00', -10800 ],
15 : [ u'UTC-02:00', -7200 ],
16 : [ u'UTC-01:00', -3600 ],
17 : [ u'UTC-00:00', 0 ],
18 : [ u'UTC+00:00', 0 ],
19 : [ u'UTC+01:00', 3600 ],
20 : [ u'UTC+02:00', 7200 ],
21 : [ u'UTC+03:00', 10800 ],
22 : [ u'UTC+03:30', 12600 ],
23 : [ u'UTC+04:00', 14400 ],
24 : [ u'UTC+04:30', 16200 ],
25 : [ u'UTC+05:00', 18000 ],
26 : [ u'UTC+05:30', 19800 ],
27 : [ u'UTC+05:45', 20700 ],
28 : [ u'UTC+06:00', 21600 ],
29 : [ u'UTC+06:30', 23400 ],
30 : [ u'UTC+07:00', 25200 ],
31 : [ u'UTC+08:00', 28800 ],
32 : [ u'UTC+09:00', 32400 ],
33 : [ u'UTC+09:30', 34200 ],
34 : [ u'UTC+10:00', 36000 ],
35 : [ u'UTC+11:00', 39600 ],
36 : [ u'UTC+12:00', 43200 ],
37 : [ u'UTC+13:00', 46800 ],
38 : [ u'UTC+14:00', 50400 ]
}
def usage():
print "Usage: cldr2qtimezone.py <path to cldr core/common> <path to qtbase>"
sys.exit()
if len(sys.argv) != 3:
usage()
cldrPath = sys.argv[1]
qtPath = sys.argv[2]
if not os.path.isdir(cldrPath) or not os.path.isdir(qtPath):
usage()
windowsZonesPath = cldrPath + "/supplemental/windowsZones.xml"
tempFileDir = qtPath + "/src/corelib/tools"
dataFilePath = qtPath + "/src/corelib/tools/qtimezoneprivate_data_p.h"
if not os.path.isfile(windowsZonesPath):
usage()
if not os.path.isfile(dataFilePath):
usage()
# [[u'version', [(u'number', u'$Revision: 7825 $')]]]
versionNumber = findTagsInFile(windowsZonesPath, "version")[0][1][0][1]
# [[u'generation', [(u'date', u'$Date: 2012-10-10 14:45:31 -0700 (Wed, 10 Oct 2012) $')]]]
generationDate = findTagsInFile(windowsZonesPath, "generation")[0][1][0][1]
mapTimezones = findTagsInFile(windowsZonesPath, "windowsZones/mapTimezones")
defaultDict = {}
windowsIdDict = {}
if mapTimezones:
for mapZone in mapTimezones:
# [u'mapZone', [(u'territory', u'MH'), (u'other', u'UTC+12'), (u'type', u'Pacific/Majuro Pacific/Kwajalein')]]
if mapZone[0] == u'mapZone':
data = {}
for attribute in mapZone[1]:
if attribute[0] == u'other':
data['windowsId'] = attribute[1]
if attribute[0] == u'territory':
data['countryCode'] = attribute[1]
if attribute[0] == u'type':
data['olsenList'] = attribute[1]
data['windowsKey'] = windowsIdToKey(data['windowsId'])
if data['windowsKey'] <= 0:
raise xpathlite.Error("Unknown Windows ID, please add \"%s\"" % data['windowsId'])
countryId = 0
if data['countryCode'] == u'001':
defaultDict[data['windowsKey']] = data['olsenList']
else:
data['countryId'] = enumdata.countryCodeToId(data['countryCode'])
if data['countryId'] < 0:
raise xpathlite.Error("Unknown Country Code \"%s\"" % data['countryCode'])
data['country'] = enumdata.country_list[data['countryId']][0]
windowsIdDict[data['windowsKey'], data['countryId']] = data
print "Input file parsed, now writing data"
GENERATED_BLOCK_START = "// GENERATED PART STARTS HERE\n"
GENERATED_BLOCK_END = "// GENERATED PART ENDS HERE\n"
# Create a temp file to write the new data into
(newTempFile, newTempFilePath) = tempfile.mkstemp("qtimezone_data_p", dir=tempFileDir)
newTempFile = os.fdopen(newTempFile, "w")
# Open the old file and copy over the first non-generated section to the new file
oldDataFile = open(dataFilePath, "r")
s = oldDataFile.readline()
while s and s != GENERATED_BLOCK_START:
newTempFile.write(s)
s = oldDataFile.readline()
# Write out generated block start tag and warning
newTempFile.write(GENERATED_BLOCK_START)
newTempFile.write("\n\
/*\n\
This part of the file was generated on %s from the\n\
Common Locale Data Repository supplemental/windowsZones.xml file\n\
%s %s\n\
\n\
http://www.unicode.org/cldr/\n\
\n\
Do not change this data, only generate it using cldr2qtimezone.py.\n\
*/\n\n" % (str(datetime.date.today()), versionNumber, generationDate) )
windowsIdData = ByteArrayData()
olsenIdData = ByteArrayData()
# Write Windows/Olsen table
newTempFile.write("// Windows ID Key, Country Enum, Olsen ID Index\n")
newTempFile.write("static const QZoneData zoneDataTable[] = {\n")
for index in windowsIdDict:
data = windowsIdDict[index]
newTempFile.write(" { %6d,%6d,%6d }, // %s / %s\n" \
% (data['windowsKey'],
data['countryId'],
olsenIdData.append(data['olsenList']),
data['windowsId'],
data['country']))
newTempFile.write(" { 0, 0, 0 } // Trailing zeroes\n")
newTempFile.write("};\n\n")
print "Done Zone Data"
# Write Windows ID key table
newTempFile.write("// Windows ID Key, Windows ID Index, Olsen ID Index, UTC Offset\n")
newTempFile.write("static const QWindowsData windowsDataTable[] = {\n")
for windowsKey in windowsIdList:
newTempFile.write(" { %6d,%6d,%6d,%6d }, // %s\n" \
% (windowsKey,
windowsIdData.append(windowsIdList[windowsKey][0]),
olsenIdData.append(defaultDict[windowsKey]),
windowsIdList[windowsKey][1],
windowsIdList[windowsKey][0]))
newTempFile.write(" { 0, 0, 0, 0 } // Trailing zeroes\n")
newTempFile.write("};\n\n")
print "Done Windows Data Table"
# Write UTC ID key table
newTempFile.write("// Olsen ID Index, UTC Offset\n")
newTempFile.write("static const QUtcData utcDataTable[] = {\n")
for index in utcIdList:
data = utcIdList[index]
newTempFile.write(" { %6d,%6d }, // %s\n" \
% (olsenIdData.append(data[0]),
data[1],
data[0]))
newTempFile.write(" { 0, 0 } // Trailing zeroes\n")
newTempFile.write("};\n\n")
print "Done UTC Data Table"
# Write out Windows ID's data
newTempFile.write("static const char windowsIdData[] = {\n")
newTempFile.write(wrap_list(windowsIdData.data))
newTempFile.write("\n};\n\n")
# Write out Olsen ID's data
newTempFile.write("static const char olsenIdData[] = {\n")
newTempFile.write(wrap_list(olsenIdData.data))
newTempFile.write("\n};\n")
print "Done ID Data Table"
# Write out the end of generated block tag
newTempFile.write(GENERATED_BLOCK_END)
s = oldDataFile.readline()
# Skip through the old generated data in the old file
while s and s != GENERATED_BLOCK_END:
s = oldDataFile.readline()
# Now copy the rest of the original file into the new file
s = oldDataFile.readline()
while s:
newTempFile.write(s)
s = oldDataFile.readline()
# Now close the old and new file, delete the old file and copy the new file in its place
newTempFile.close()
oldDataFile.close()
os.remove(dataFilePath)
os.rename(newTempFilePath, dataFilePath)
print "Data generation completed, please check the new file at " + dataFilePath