[prev in list] [next in list] [prev in thread] [next in thread] 

List:       kde-core-devel
Subject:    KDateTime: new revised version
From:       David Jarvie <lists () astrojar ! org ! uk>
Date:       2005-11-23 23:33:31
Message-ID: 200511232333.54106.lists () astrojar ! org ! uk
[Download RAW message or body]

I attach a new revision of kdatetime.h. For size reasons, I've made 
kdatetime.cpp available for download at 
http://www.astrojar.org.uk/linux/download/kdatetime.cpp rather than attach 
it. I hope that I've addressed all the comments made.

- There is now a non-explicit constructor which takes just a QDateTime as 
parameter, and uses the UTC or LocalTime spec of the QDateTime.

- The fromString() parsing code is completely rewritten to avoid copyright 
problems.

- I've added support for RFC2822 format strings.

- I've changed the return type of toUTC() and toLocal() to KDateTime, and 
added toZone(). These provide conversion between time zones in KDateTime. I 
think that this is the most natural way to convert date/times between 
different zones.

It's still untested - once things stabilise enough, I'll write the test 
program.

-- 
David Jarvie.
KAlarm author and maintainer.
http://www.astrojar.org.uk/linux/kalarm.html

["kdatetime.h" (text/x-c++hdr)]

/*
    This file is part of the KDE libraries
    Copyright (c) 2005 David Jarvie <software@astrojar.org.uk>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

/** @file
 * Date/times with associated time zone
 * @author David Jarvie <software@astrojar.org.uk>.
 */

#ifndef _KDATETIME_H_
#define _KDATETIME_H_

#include <ktimezones.h>
#include "kdelibs_export.h"

class KDateTimePrivate;

/**
 * @short A class representing a date and time with an associated time zone
 *
 * Topics:
 *  - @ref intro
 *  - @ref manipulation
 *  - @ref compatibility
 *
 * @section intro Introduction
 *
 * The class KDateTime combines a date and time with support for an
 * associated time zone. When manipulating KDateTime objects, their time zones
 * are automatically taken into account.
 *
 * The time zones which KDateTime supports are:
 * - the UTC time zone
 * - a specified KTimezone object
 * - local clock time, using the current system time zone. In this case, if the
 *   system time zone changes, the UTC time for the instance will change
 *   correspondingly.
 *
 * To set the time zone to a given value use one of the setTimeZone() methods,
 * to get the time zone call timeZone(), isUTC() or isLocal().
 *
 * @section manipulation Date and Time Manipulation
 *
 * A KDateTime object can be created by passing a date and time in its
 * constructor, together with a time zone specification.
 *
 * If both the date and time are null, isNull() returns true.
 * If both the date and the time are valid, isValid() returns true.
 *
 * A KDateTime object can be converted to QDateTime by using toUTC() or
 * toLocal(), or to a UNIX time stamp since 1st January 1970 by toTime_t().
 * There is no facility in this class to convert to another KTimezone: use
 * KTimezone::convert() to do this.
 *
 * The date and time can be set either in the constructor, or afterwards by
 * calling setDate() and setTime(). date() and time() return the date and time.
 *
 * You can increment or decrement the date/time using addSecs(), addDays(),
 * addMonths() and addYears(). The interval between two date/time values can
 * be found using secsTo() or daysTo().
 *
 * The comparison operators (operator==(), operator<(), etc.) all take the time
 * zone properly into account; if the two KDateTime objects have different time
 * zones, they are first converted to UTC before the comparison is performed.
 *
 * @section compatibility QDateTime Compatibility
 *
 * KDateTime's interface is designed to be as compatible as possible with that
 * of QDateTime, but with adjustments to cater for time zone handling. Because
 * QDateTime lacks virtual methods, KDateTime is not inherited from QDateTime,
 * but instead is implemented using a private QDateTime object.
 * @todo maybe other notes here?
 *
 * @see KTimezone, KSystemTimezones, QDateTime, QDate, QTime
 * @author David Jarvie \<software@astrojar.org.uk\>.
 * @since 4.0
 */
class KDECORE_EXPORT KDateTime
{
  public:
    /** Format for strings representing date/time values. */
    enum DateFormat
    {
        ISODate,        /**< ISO 8601 format, i.e. YYYY-MM-DDThh:mm:ssTZ, where TZ
                         *    is the time zone offset (blank for local time,
                         *    Z for UTC, or ±hhmm for an offset from UTC)
                         */
        RFC2822Date,    /**< RFC 2822 format without day of the week,
                         *   i.e. DD Mon YYYY hh:mm:ss ±hhmm
                         */
        RFC2822DateDay, /**< RFC 2822 format including day of the week,
                         *   i.e. Day, DD Mon YYYY hh:mm:ss ±hhmm
                         */
        QtTextDate,     /**< Same format as Qt::TextDate (i.e. Day Mon DD hh:mm:ss YYYY)
                         *   with, if not local time, the UTC offset appended
                         */
        LocalDate       /**< Same format as Qt::LocalDate (i.e. locale dependent)
                         *   with, if not local time, the UTC offset appended
                         */
    };

  
    /**
     * Constructs an invalid date/time using local clock time.
     */
    KDateTime();

    /**
     * Constructs a date/time with associated time zone. The time is
     * set to 00:00:00.
     *
     * @param date date in the time zone @p tz
     * @param tz   time zone
     */
    KDateTime(const QDate &date, const KTimezone *tz);

    /**
     * Constructs a date/time with associated time zone.
     *
     * @param date date in the time zone @p tz
     * @param time time in the time zone @p tz
     * @param tz   time zone
     */
    KDateTime(const QDate &date, const QTime &time, const KTimezone *tz);

    /**
     * Constructs a date/time with associated time zone.
     * If @p dt is specified as a UTC time (i.e. @c dt.timeSpec() is @c Qt::UTC),
     * it is first converted to local time in time zone @p tz before being stored.
     *
     * @param dt date and time
     * @param tz time zone
     */
    KDateTime(const QDateTime &dt, const KTimezone *tz);

    /**
     * Constructs a date/time expressed in either UTC or local clock time. The
     * time component is set to 00:00:00.
     *
     * @param date date in the time zone indicated by @p spec
     * @param spec @c Qt::UTC to use UTC time zone, or @c Qt::LocalTime to use
     *             local clock time
     */
    explicit KDateTime(const QDate &date, Qt::TimeSpec spec = Qt::LocalTime);

    /**
     * Constructs a date/time expressed in either UTC or local clock time.
     *
     * @param date date in the time zone indicated by @p spec
     * @param time time in the time zone indicated by @p spec
     * @param spec @c Qt::UTC to use UTC time zone, or @c Qt::LocalTime to use
     *             local clock time
     */
    KDateTime(const QDate &date, const QTime &time, Qt::TimeSpec spec = Qt::LocalTime);

    /**
     * Constructs a date/time expressed in either UTC or local clock time.
     * If @p dt is given with a different time specification than @p spec (one
     * of @p spec and @c dt.timeSpec() is @c Qt::UTC, and the other is
     * @c Qt::LocalTime), @p dt is first converted to either UTC or local time
     * (as given by @p spec) before being stored. The conversion is done using
     * the current system time zone.
     *
     * @param dt   date and time
     * @param spec @c Qt::UTC to use UTC time zone, or @c Qt::LocalTime to use
     *             local clock time
     */
    KDateTime(const QDateTime &dt, Qt::TimeSpec spec);

    /**
     * Constructs a date/time from a QDateTime.
     * The KDateTime is expressed in either UTC or local clock time, according
     * to @p dt.timeSpec().
     *
     * @param dt date and time
     */
    KDateTime(const QDateTime &dt);

    KDateTime(const KDateTime &other);
    ~KDateTime();

    KDateTime &operator=(const KDateTime &other);

    /**
     * Returns whether the date/time is null.
     *
     * @return @c true if both date and time are null, else @c false
     * @see isValid(), QDateTime::isNull()
     */
    bool isNull() const;

    /**
     * Returns whether the date/time is valid.
     *
     * @return @c true if both date and time are valid, else @c false
     * @see isNull(), QDateTime::isValid()
     */
    bool isValid() const;

    /**
     * Returns the date part of the date/time. The value returned should be
     * interpreted in terms of the instance's time zone.
     *
     * @return date value
     * @see time(), dateTime()
     */
    QDate date() const;

    /**
     * Returns the time part of the date/time. The value returned should be
     * interpreted in terms of the instance's time zone.
     *
     * @return time value
     * @see date(), dateTime()
     */
    QTime time() const;

    /**
     * Returns the date/time component of the instance, ignoring the time
     * zone. The value returned should be interpreted in terms of the
     * instance's time zone. The returned value's @c timeSpec() value will
     * be @c Qt::UTC if the instance is a UTC time, else @c Qt::LocalTime.
     *
     * @return date/time
     * @see date(), time()
     */
    QDateTime dateTime() const;

    /**
     * Returns the time zone for the date/time. If the date/time is specified
     * as a UTC time, a UTC time zone is always returned.
     *
     * @return time zone, or null if a local clock time
     * @see isUTC(), isLocal()
     */
    const KTimezone *timeZone() const;

    /**
     * Returns whether the date/time is a local clock time.
     *
     * @return @c true if local clock time
     * @see isUTC(), timeZone()
     */
    bool isLocal() const;

    /**
     * Returns whether the date/time is a UTC time.
     *
     * @return @c true if UTC
     * @see isLocal(), timeZone()
     */
    bool isUTC() const;

    /**
     * Returns the time converted to UTC.
     *
     * @return converted time
     * @see toLocal(), toZone(), toTime_t(), KTimezone::convert()
     */
    KDateTime toUTC() const;

    /**
     * Returns the time converted to the local clock time.
     *
     * @return converted time
     * @see toUTC(), toZone(), KTimezone::convert()
     */
    KDateTime toLocal() const;

    /**
     * Returns the time converted to a specified time zone.
     *
     * @param zone time zone to convert to
     * @return converted time
     * @see toUTC(), toLocal(), KTimezone::convert()
     */
    KDateTime toZone(const KTimezone *zone) const;

    /**
     * Converts the time to a UTC time, measured in seconds since 00:00:00 UTC
     * 1st January 1970 (as returned by time(2)).
     *
     * @return converted time, or -1 if the date is out of range for time_t
     * @see setTime_t()
     */
    uint toTime_t() const;

    /**
     * Sets the date part of the date/time.
     *
     * @param date new date value
     * @see date(), setTime(), setTimeZone(), setTime_t()
     */
    void setDate(const QDate &date);

    /**
     * Sets the time part of the date/time.
     *
     * @param time new time value
     * @see time(), setDate(), setTimeZone(), setTime_t()
     */
    void setTime(const QTime &time);

    /**
     * Sets the date/time part of the instance, leaving the time zone unaffected.
     * If @p dt is a local time (\code dt.timeSpec() == Qt::LocalTime \endcode)
     * and the instance is either UTC or has a specified time zone, or if @p dt
     * is UTC and the instance is in local clock time, @p dt is first converted
     * to the instance's time zone or local time (as appropriate) before being
     * stored. If converting to or from local time, the conversion is done using
     * the current system time zone.
     *
     * @param dt date and time
     */
    void setDateTime(const QDateTime &dt);

    /**
     * Sets the stored time to be expressed as either UTC or local clock time.
     * Any previous time zone is forgotten. The stored time value is left
     * unchanged, so that if the time zone or UTC/local clock time indicator has
     * changed, it will now represent a different UTC time.
     *
     * @param spec @c Qt::UTC to use UTC time zone, or @c Qt::LocalTime to use
     *             local clock time
     * @see timeZone(), setTimeZone(const KTimezone*)
     */
    void setTimeZone(Qt::TimeSpec spec);

    /**
     * Sets the time zone in which the date/time is expressed.
     * The stored time value is left unchanged, so that if the time zone has
     * changed, it will now represent a different UTC time.
     *
     * To set the time zone to UTC or to local time, use setTimeZone(Qt::TimeSpec).
     *
     * @param tz new time zone, or null to change to local clock time
     * @see timeZone(), setTimeZone(Qt::TimeSpec)
     */
    void setTimeZone(const KTimezone *tz);

    /**
     * Sets the time to a UTC time, measured in seconds since 00:00:00 UTC
     * 1st January 1970 (as returned by time(2)). If the KDateTime instance is
     * expressed in either a time zone or as local clock time, the UTC time is
     * first converted to the instance's time zone (the current system time
     * zone if using local clock time) before being stored.
     *
     * @param seconds UTC time, measured in seconds since 00:00:00 UTC
     *                1st January 1970 (as returned by time(2))
     * @see setTime(), setDate(), toTime_t()
     */
    void setTime_t(uint seconds);

    /**
     * Returns a date/time @p secs seconds later than the stored date/time.
     * The calculation is done in UTC to ensure that clock changes (e.g. daylight
     * savings) in the time zpme do not affect the result. The result is
     * expressed in the same time zone as the original instance.
     *
     * @return resultant date/time
     * @see addDays(), addMonths(), addYears(), secsTo()
     */
    KDateTime addSecs(int secs) const;

    /**
     * Returns a date/time @p days days later than the stored date/time.
     * The result is expressed in the same time zone as the original instance.
     *
     * @return resultant date/time
     * @see addSecs(), addMonths(), addYears(), daysTo()
     */
    KDateTime addDays(int days) const;

    /**
     * Returns a date/time @p months months later than the stored date/time.
     * The result is expressed in the same time zone as the original instance.
     *
     * @return resultant date/time
     * @see addSecs(), addDays(), addYears(), daysTo()
     */
    KDateTime addMonths(int months) const;

    /**
     * Returns a date/time @p years years later than the stored date/time.
     * The result is expressed in the same time zone as the original instance.
     *
     * @return resultant date/time
     * @see addSecs(), addDays(), addMonths(), daysTo()
     */
    KDateTime addYears(int years) const;

    /**
     * Calculates the number of days from this date/time to the @p other date/time.
     * In calculating the result, @p other is first converted to this instance's
     * time zone. The number of days difference is then calculated ignoring
     * the time parts of the two date/times. For example, if this date/time
     * was 13:00 on 1 January 2000, and @p other was 02:00 on 2 January 2000,
     * the result would be 1.
     *
     * @param other other date/time
     * @return number of days difference
     * @see secsTo(), addDays()
     */
    int daysTo(const KDateTime &other) const;

    /**
     * Returns the number of seconds from this date/time to the @p other date/time.
     * Before performing the comparison, the two datetimes are converted to UTC
     * to ensure that the result is correct if one of the two datetimes has
     * daylight saving time (DST) and the other doesn't.
     *
     * @param other other date/time
     * @return number of seconds difference
     * @see addSecs(), daysTo()
     */
    int secsTo(const KDateTime &other) const;

    /**
     * Returns the date/time as a string. The @p format parameter determines the
     * format of the result string. The @p format codes used for the date and time
     * components are those defined for QDateTime::toString(). For the time zone
     * component, the following codes may be used:
     *
     * ZZZ  - the abbreviated time zone code, e.g. UTC, EDT, BST.
     * ZZZZ - the name of the time zone, e.g. Europe/London. This is system dependent.
     * uu   - the UTC offset of the time zone in hours, e.g. -02. If the offset
     *        is not a whole number of hours, the output is the same as for "uuu".
     * uuu  - the UTC offset of the time zone in hours and minutes, e.g. -0200.
     * uuuu - the UTC offset of the time zone in hours and minutes, e.g. +02:00.
     *
     * Note that only one of these codes may be used.
     *
     * @param format format for the string
     * @return formatted string
     * @see fromString(), QDateTime::toString()
     */
    QString toString(const QString &format) const;

    /**
     * Returns the date/time as a string, formatted according to the @p format
     * parameter.
     *
     * @param format format for output string
     * @return formatted string
     * @see fromString(), QDateTime::toString()
     */
    QString toString(DateFormat format = ISODate) const;

    /**
     * Returns the QDateTime represented by @p string, using the @p format given.
     *
     * This method is the inverse of toString(DateFormat), except that it
     * can only return a UTC or local clock time. Time zone information cannot
     * be returned since an offset from UTC only partially specifies a time zone.
     *
     * @param string string to convert
     * @param format format code. LocalDate cannot be used here.
     * @return QDateTime value as either a UTC or local clock time, or an
     *         invalid QDateTime if either parameter is invalid
     * @see toString(), QString::fromString()
     */
    static QDateTime fromString(const QString &string, DateFormat format = ISODate);

    /**
     * Returns the QDateTime represented by @p string, using the @p format given.
     * The @p format codes are the same as those for toString(), but time zone
     * names (codes ZZZ and ZZZZ) are not allowed since they cannot be
     * interpreted. Any UTC offset is used to adjust the resultant QDateTime. If
     * a UTC offset is present, the time spec of the result will be @c Qt::UTC;
     * otherwise the result will be @c Qt::LocalTime.
     *
     * @param string string to convert
     * @param format format string
     * @return QDateTime value, or an invalid QDateTime if either parameter is
     *         invalid
     * @see toString()
     */
    static QDateTime fromString(const QString &string, const QString &format);

    /**
     * Returns the KDateTime represented by @p string, using the @p format
     * given, and using a specified time zone collection as the source of
     * time zone definitions. The @p format codes are the same as those for
     * toString(). Only one time zone or UTC offset code may be used.
     *
     * If any time zone information is present in the string, the function
     * attempts to find a matching time zone in the @p zones collection. A time
     * zone name (format code ZZZZ) will provide an unambiguous look up in
     * @p zones. Any other type of time zone information (an abbreviated time
     * zone code (ZZZ) or UTC offset (uu, uuu, uuuu) is searched for in 
     * @p zones and if only one time zone is found to match, the result is set
     * to that zone. If more than one match is found, the action taken is
     * determined by @p utcIfAmbiguous: if @p utcIfAmbiguous is true and
     * a UTC offset is specified, a UTC time will be returned; otherwise an
     * invalid KDateTime is returned. If the time zone information does not
     * match any of the time zones in @p zones, an invalid KDateTime is returned.
     *
     * If no time zone information is present in the string, a local clock time
     * is returned.
     *
     * @param string string to convert
     * @param format format string
     * @param zones time zone collection 
     * @return KDateTime value, or an invalid KDateTime if a parameter is
     *         invalid, if time zone information doesn't match any in @p zones,
     *         or if the time zone information is ambiguous and @p utcIfAmbiguous
     *         is false
     * @see toString()
     */
    static KDateTime fromString(const QString &string, const QString &format,
                                const KTimezones &zones, bool utcIfAmbiguous = false);

    /**
     * Check whether this date/time is simultaneous with another.
     * The comparison takes time zones into account; if the two instances have
     * different time zones, they are first converted to UTC before comparing.
     *
     * @return @c true if the two instances represent the same time, @c false otherwise
     */
    bool operator==(const KDateTime &other) const;
    bool operator!=(const KDateTime &other) const { return !(*this == other); }

    /**
     * Check whether this date/time is earlier than another.
     * The comparison takes time zones into account; if the two instances have
     * different time zones, they are first converted to UTC before comparing.
     *
     * @return @c true if this instance represents an earlier time than @p other,
     *         @c false otherwise
     */
    bool operator<(const KDateTime &other) const;
    bool operator<=(const KDateTime &other) const { return !(other < *this); }
    bool operator>(const KDateTime &other) const { return other < *this; }
    bool operator>=(const KDateTime &other) const { return !(*this < other); }

    friend QDataStream & operator<<(QDataStream &out, const KDateTime &dateTime);
    friend QDataStream & operator>>(QDataStream &in, KDateTime &dateTime);

  private:
    KDateTimePrivate *d;
};

#if 0
QDataStream & operator<<(QDataStream &out, const KDateTime &dateTime);
QDataStream & operator>>(QDataStream &in, KDateTime &dateTime);
#endif

#endif


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic