cargo chrono 0.2.0
v0.2.0

latest releases: 0.4.45, 0.4.44, 0.4.43...
11 years ago

Original announcements:

I've finally got the initial design of Chrono 0.2 working. It took so much time, partially because I'm working on dozens of other projects including Rust libraries. It solves one of the major annoyance with Chrono, so I'm glad that this new design is promising.

Time zones in Chrono 0.1

As always, I start by pointing to Erik Naggum's excellent essay about date and time. (Yes, I'm terrible at story telling and I won't say a lot about that.) Most importantly, the core aspect of time zone is that
it is ultimately a political creation rather than a natural necessity. This complicates lots of things, though Author David Olson and others have done a tremendously important work in this regard.

There are several problems with time zones:

  1. There is no reliable way to handle the local date in the future.
  2. There can exist a local date which occurred in two or more instants.
  3. There can exist a local date which never has been occurred.
  4. The conversion process itself is seriously annoying and easy to make a mistake.

(If you are interested in the timekeeping, you'll realize that this list equally applies to leap seconds. I had to deal with them in Chrono as well, and chose to make them invisible to the normal usage.)

In fact, Chrono's original Offset design does explicitly account for these problems. In Chrono, the local date is a concept only meaningful to accessors and formatting routines, eliminating the very source of 1. The possibility of 2 and 3 is handled via the LocalResult enum, while 4 is handled via... delegating everything to the Offset. This decision is partly because we would only have a handful number of Offset implementations, so we have to implement them anyway. In the end, we had something like this:

pub trait Offset: Clone + Show {
    fn local_minus_utc(&self) -> Duration;

    fn from_local_date(&self, local: &NaiveDate) -> LocalResult<Date<Self>>;
    fn from_local_time(&self, local: &NaiveTime) -> LocalResult<Time<Self>>;
    fn from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<DateTime<Self>>;

    fn to_local_date(&self, utc: &NaiveDate) -> NaiveDate;
    fn to_local_time(&self, utc: &NaiveTime) -> NaiveTime;
    fn to_local_datetime(&self, utc: &NaiveDateTime) -> NaiveDateTime;

    fn ymd(&self, year: i32, month: u32, day: u32) -> Date<Self> { ... }
    // other constructors follow
}

pub struct DateTime<Off> {
    datetime: NaiveDateTime,
    offset: Off
}

// Date and Time follows

This sounds good. You can put the offset data into the timezone-aware DateTime, and use it to convert to the local date (to_local_date). In the converse, DateTime has to be created from Offset so that it converts to the internal representation in UTC (from_local_date).

But you might wonder: why is local_minus_utc separate from to_local_datetime? The latter can be implemented via the former, right? Yes! In the current implementation the latter is redundant. And this redundancy suggests a bigger problem.

Originally, to_local_datetime was to be used in the absence of the exact offset to UTC. This alone is enough for converting UTC to the local time, and it is still used in the Offset conversion where the original value is converted to UTC then to the target time zone. But this is inefficient, especially if we have a large table of zone transitions. Therefore we have local_minus_utc for caching the calculated current offset. The caller was expected to call local_minus_utc for converting the current value to UTC and to_local_datetime etc. for other cases. For the fixed-offset time zones like UTC these methods will be largely a simple arithmetic, so we only pay what we use.

In the reality this scheme didn't work well. Local was an example of the glaring problem; since it has to cache the value, it should have a field, but that meant that we need to create a Local instance every time we convert to the local date! This defies the simple interface like dt.with_offset(UTC), and since such Local instance doesn't know about the exact offset, we have a separate flag indicating the offset is correct or not. (In Rust, this would translate to Option<FixedOffset>.) This even breaks the original premise of "only paying what we actually use".

After I realized this problem, I'd tried several solutions and spectacularly failed. It was clear that we really need two kinds of types, but I was not sure how to do that.

Time zones in Chrono 0.2

Associated types, originally proposed in RFC #195, were a game changer for this problem. They allow for two types to be smoothly connected in the compile time. The resulting design is as follows:

pub trait Offset: Sized + Clone + fmt::Show {
    fn local_minus_utc(&self) -> Duration;
}

pub trait TimeZone: Sized {
    type Offset: Offset;

    fn from_offset(offset: &Self::Offset) -> Self;

    fn offset_from_local_date(&self, local: &NaiveDate) -> LocalResult<Self::Offset>;
    fn offset_from_local_time(&self, local: &NaiveTime) -> LocalResult<Self::Offset>;
    fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<Self::Offset>;

    fn offset_from_utc_date(&self, utc: &NaiveDate) -> Self::Offset;
    fn offset_from_utc_time(&self, utc: &NaiveTime) -> Self::Offset;
    fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> Self::Offset;

    // helpers and constructors follow
}

pub struct DateTime<Tz: TimeZone> {
    datetime: NaiveDateTime,
    offset: Tz::Offset,
}

// Date and Time follows

This new design directly shows that we are dealing with two different types! TimeZone creates an Offset which is a storage-oriented type, which can be converted back to the TimeZone via from_offset. TimeZone is used for creating date and time values, while Offset is used for converting to the local time. I originally tried to avoid separate trait for local_minus_utc, but ultimately abandoned that plan to make dt.offset().local_minus_utc() possible.

There are a set of TimeZones and Offsets available:

TimeZone instance Offset instance
UTC UTC
FixedOffset FixedOffset
Local FixedOffset
TzFile (*) TzFileOffset (*)
TzRule (*) TzRuleOffset (*)

(* Some instances are under the development.)

One can note that some time zones are their own offsets, as they do not have an additional data (i.e. cache) for the storage, and Local reuses the FixedOffset as Local itself has no state. Other time zones have to cache its offset and the transition data, hence separate offset types.

TzFile and TzRule is a part of tzdata support; they will be typically used as a reference-counted version, such as Rc<TzFile> or Arc<TzRule>, to avoid the deep copying (which is common in Chrono). TzRule implements the rule string in POSIX TZ environment variable, which is not that useful by its own (since we can use Local anyway), but it's TzFile's solution to the aforementioned problem 1: the future zone transition is encoded as a form of TzRule, and we need to implement it.

At the end this new design is quite promising, but even after #![feature(associated_types)] is gone associated types are still cutting edge features. I had to disable debuginfo due to the Rust issue #21010, for example. Hopefully though, this shall not affect the validity of this design.

New formatting and parsing API

Chrono 0.2 has three different pieces of new APIs redesigned for formatting and parsing:

  • Formatting syntax representation ("items") and parsing
  • Formatting with items
  • Parsing with items

Altogether they form an advanced formatting facility in Chrono 0.2.
I'll try to briefly discuss their designs and justifications.

Formatting Items

In Chrono, a formatting item is a unit of formatting or parsing. For example a strftime-like format string %Y-%m-%d has five different formatting items: %Y, -, %m, - and %d. Chrono decouples a formatting syntax from the actual meaning of formatting items, so they have the following (somewhat verbose) internal representations:

[Item::Numeric(Numeric::Year, Pad::Zero),
 Item::Literal("-"),
 Item::Numeric(Numeric::Month, Pad::Zero),
 Item::Literal("-"),
 Item::Numeric(Numeric::Day, Pad::Zero)]

This decoupling allows Chrono to support multiple formatting syntax, such as YYYY-MM-DD or Go-like 2006-01-02 instead. Also, Chrono can have "hidden" formatting items that can be used for internal purposes. RFC 2822 and 3339 support is implemented in this way.

The formatting item is a good abstraction, but every abstraction comes with a complexity. In the case of Chrono the complexity arises from the desire to avoid allocation. The number of formatting items is proportional to the length of format string in the worst case, so we cannot blindly collect items into a collection. Instead, Chrono returns an Iterator of formatting items and directly consumes that iterator for printing the date and time. Therefore the following identity holds:

assert_eq!(StrftimeItems::new("%Y-%m-%d").collect::<Vec<_>>(),
           [Item::Numeric(Numeric::Year, Pad::Zero),
            Item::Literal("-"),
            Item::Numeric(Numeric::Month, Pad::Zero),
            Item::Literal("-"),
            Item::Numeric(Numeric::Day, Pad::Zero)]);

I believe this redesign has a maximal flexibility while retaining an ability to avoid std at all.

Formatting with Items

Formatting with items is done with a new format_with_items method. The original format method is now a thin wrapper over that.

This part of Chrono remains relatively unchanged, but there are some notable small changes which deserve the explanation:

  • The original format had a bug with leap seconds: Instead of printing 23:59:60.234567890, it would print 23:59:59.1234567890. It originates from Chrono's unique handling of leap seconds, and has been fixed in Chrono 0.2.
  • There are Numeric::Nanosecond and Fixed::Nanosecond. The former corresponds to strftime's %f specifier and was present since Chrono 0.1. The latter is a new formatting item which may print nothing, .###, .###### or .######### depending on the available accuracy. (An empty string is for the whole number of seconds.) This "adaptive" version turned out to be much more useful for parsing.
  • Numeric::Timestamp (%s) is now supported. It was delayed due to the proper local date/time handling.
  • While this change is quite subtle, Numeric::Year (%Y) and Numeric::IsoYear (%G) now has an explicit sign for years not between 1 BCE and 9999 CE. It is a necessity from bijective parsing, which means that once printed, any valid date and time can be parsed into the original value. This particular scheme is adopted from ISO 8601:2004, so this is not really Chrono's own invention.

Parsing with Items

Okay, this is a fun part. Basically Chrono 0.2 has the following parsing algorithm:

  1. A fixed string parses as is: It has to appear in the input string as is.
  2. A sequence of one or more whitespace consumes zero or more whitespace.
  3. Most numeric items (Numeric::*) have a predefined parsing width, the maximal number of digits that can be consumed. They consume zero or more whitespace followed by one or more but limited number of digits. The exception is made to Numeric::Year and Numeric::IsoYear, which may accept an arbitrary number of digits when preceded by a sign.
  4. Fixed items (Fixed::*) have their own parsing logics, but normally does not consume preceding whitespace. They also normally ignore cases.
  5. At the end of the formatting items, the whole input string should have been consumed.

This is modelled after strptime's parsing algorithm, which seems to handle lots of corner cases. This allows a lax input like 2014-2-6 for a format string %Y-%m-%d. The fixed parsing width allows a format string like %Y%m%d which would accept strings like 20140206.

Parsing is daunting work, implemented with two rather big modules (chrono::format::{parse,scan}), but it's actually an easy part. Parsing only yields different date/time parts, which has to be merged into actual values via the resolution algorithm.

As an easy example, consider RFC 2822. RFC 2822 date and time format has a day of week part, which should be consistent to other date parts when specified. But strptime-based parse would happily accept inconsistent input:

>>> import time
>>> time.strptime('Wed, 31 Dec 2014 04:26:40 +0000',
                  '%a, %d %b %Y %H:%M:%S +0000')
time.struct_time(tm_year=2014, tm_mon=12, tm_mday=31,
                 tm_hour=4, tm_min=26, tm_sec=40,
                 tm_wday=2, tm_yday=365, tm_isdst=-1)
>>> time.strptime('Thu, 31 Dec 2014 04:26:40 +0000',
                  '%a, %d %b %Y %H:%M:%S +0000')
time.struct_time(tm_year=2014, tm_mon=12, tm_mday=31,
                 tm_hour=4, tm_min=26, tm_sec=40,
                 tm_wday=3, tm_yday=365, tm_isdst=-1)

Resolving date/time parts is littered with lots of corner cases, and that's why common date/time parsers do not correctly implement it; as far as I know, glibc, Python and JodaTime completely ignores the resolution. Therefore I'm glad to announce that Chrono 0.2 has a complete and known-to-be-correct resolution algorithm.

Chrono has a dedicated date/time part storage called Parsed. The resolution algorithm is hard to describe as is, but the relevant source code is relatively well-commented and worth reading if you are interested in the algorithm.

Chrono 0.3?

Maybe this might be an early assumption, but Chrono 0.2 is intended to be a stable base of the future API evolution. The very main design decision was already in 0.1, but 0.2 completes and fixes the biggest problem with 0.1.

There are some issues I've thought about 0.3. Some of them will be definitely implemented in 0.3 (e.g. tzfile support), some others are somewhat illusive (e.g. additional format syntax). But these issues do not replace the users' feedback. Personally I'd like to thank /u/savage884, who brought the problem of local date handling in the /r/rust post. This post crucially helped me finishing the work and releasing 0.2. I wish others give a feedback for Chrono like that, so Chrono doesn't remain an library "considered annoying but designed so", which situation I really don't like.


Added

  • Offset is splitted into TimeZone (constructor) and Offset (storage) types.
    You would normally see only the former, as the latter is mostly an implementation detail.
    Most importantly, Local now can be used to directly construct timezone-aware values.

    Some types (currently, UTC and FixedOffset) are both TimeZone and Offset, but others aren't (e.g. Local is not what is being stored to each DateTime values).

  • LocalResult::map convenience method has been added.

  • TimeZone now allows a construction of DateTime values from UNIX timestamp, via timestamp and timestamp_opt methods.

  • TimeZone now also has a method for parsing DateTime, namely datetime_from_str.

  • The following methods have been added to all date and time types:

    • checked_add
    • checked_sub
    • format_with_items
  • The following methods have been added to all timezone-aware types:

    • timezone
    • with_timezone
    • naive_utc
    • naive_local
  • parse_from_str method has been added to all naive types and DateTime<FixedOffset>.

  • All naive types and instances of DateTime with time zones UTC, Local and FixedOffset implement the FromStr trait. They parse what std::fmt::Debug would print.

  • chrono::format has been greatly rewritten.

    • The formatting syntax parser is modular now, available at chrono::format::strftime.

    • The parser and resolution algorithm is also modular, the former is available at chrono::format::parse while the latter is available at chrono::format::parsed.

    • Explicit support for RFC 2822 and 3339 syntaxes is landed.

    • There is a minor formatting difference with atypical values, e.g. for years not between 1 BCE and 9999 CE.

Changed

  • Most uses of Offset are converted to TimeZone. In fact, all user-facing code is expected to be Offset-free.

  • [Naive]DateTime::*num_seconds_from_unix_epoch* methods have been renamed to simply timestamp or from_timestamp*. The original names have been deprecated.

Removed

  • Time has been removed. This also prompts a related set of methods in TimeZone.

    This is in principle possible, but in practice has seen a little use because it can only be meaningfully constructed via an existing DateTime value.
    This made many operations to Time unintuitive or ambiguous, so we simply let it go.

    In the case that Time is really required, one can use a simpler NaiveTime.
    NaiveTime and NaiveDate can be freely combined and splitted, and TimeZone::from_{local,utc}_datetime can be used to convert from/to the local time.

  • with_offset method has been removed. Use with_timezone method instead.
    (This is not deprecated since it is an integral part of offset reform.)

Don't miss a new chrono release

NewReleases is sending notifications on new releases.