Date and time library for Rust

Overview

Chrono: Date and Time for Rust

Chrono GitHub Actions Chrono on crates.io Chrono on docs.rs Join the chat at https://gitter.im/chrono-rs/chrono

It aims to be a feature-complete superset of the time library. In particular,

  • Chrono strictly adheres to ISO 8601.
  • Chrono is timezone-aware by default, with separate timezone-naive types.
  • Chrono is space-optimal and (while not being the primary goal) reasonably efficient.

There were several previous attempts to bring a good date and time library to Rust, which Chrono builds upon and should acknowledge:

Any significant changes to Chrono are documented in the CHANGELOG.md file.

Usage

Put this in your Cargo.toml:

[dependencies]
chrono = "0.4"

Features

Chrono supports various runtime environments and operating systems, and has several features that may be enabled or disabled.

Default features:

  • alloc: Enable features that depend on allocation (primarily string formatting)
  • std: Enables functionality that depends on the standard library. This is a superset of alloc and adds interoperation with standard library types and traits.
  • clock: enables reading the system time (now), independent of whether std::time::SystemTime is present, depends on having a libc.

Optional features:

  • wasmbind: Enable integration with wasm-bindgen and its js-sys project
  • serde: Enable serialization/deserialization via serde.
  • unstable-locales: Enable localization. This adds various methods with a _localized suffix. The implementation and API may change or even be removed in a patch release. Feedback welcome.

See the cargo docs for examples of specifying features.

Overview

Duration

Chrono currently uses its own [Duration] type to represent the magnitude of a time span. Since this has the same name as the newer, standard type for duration, the reference will refer this type as OldDuration.

Note that this is an "accurate" duration represented as seconds and nanoseconds and does not represent "nominal" components such as days or months.

When the oldtime feature is enabled, [Duration] is an alias for the time::Duration type from v0.1 of the time crate. time v0.1 is deprecated, so new code should disable the oldtime feature and use the chrono::Duration type instead. The oldtime feature is enabled by default for backwards compatibility, but future versions of Chrono are likely to remove the feature entirely.

Chrono does not yet natively support the standard Duration type, but it will be supported in the future. Meanwhile you can convert between two types with Duration::from_std and Duration::to_std methods.

Date and Time

Chrono provides a DateTime type to represent a date and a time in a timezone.

For more abstract moment-in-time tracking such as internal timekeeping that is unconcerned with timezones, consider time::SystemTime, which tracks your system clock, or time::Instant, which is an opaque but monotonically-increasing representation of a moment in time.

DateTime is timezone-aware and must be constructed from the TimeZone object, which defines how the local date is converted to and back from the UTC date. There are three well-known TimeZone implementations:

  • Utc specifies the UTC time zone. It is most efficient.

  • Local specifies the system local time zone.

  • FixedOffset specifies an arbitrary, fixed time zone such as UTC+09:00 or UTC-10:30. This often results from the parsed textual date and time. Since it stores the most information and does not depend on the system environment, you would want to normalize other TimeZones into this type.

DateTimes with different TimeZone types are distinct and do not mix, but can be converted to each other using the DateTime::with_timezone method.

You can get the current date and time in the UTC time zone (Utc::now()) or in the local time zone (Local::now()).

use chrono::prelude::*;

let utc: DateTime<Utc> = Utc::now();       // e.g. `2014-11-28T12:45:59.324310806Z`
let local: DateTime<Local> = Local::now(); // e.g. `2014-11-28T21:45:59.324310806+09:00`

Alternatively, you can create your own date and time. This is a bit verbose due to Rust's lack of function and method overloading, but in turn we get a rich combination of initialization methods.

use chrono::prelude::*;
use chrono::offset::LocalResult;

let dt = Utc.ymd(2014, 7, 8).and_hms(9, 10, 11); // `2014-07-08T09:10:11Z`
// July 8 is 188th day of the year 2014 (`o` for "ordinal")
assert_eq!(dt, Utc.yo(2014, 189).and_hms(9, 10, 11));
// July 8 is Tuesday in ISO week 28 of the year 2014.
assert_eq!(dt, Utc.isoywd(2014, 28, Weekday::Tue).and_hms(9, 10, 11));

let dt = Utc.ymd(2014, 7, 8).and_hms_milli(9, 10, 11, 12); // `2014-07-08T09:10:11.012Z`
assert_eq!(dt, Utc.ymd(2014, 7, 8).and_hms_micro(9, 10, 11, 12_000));
assert_eq!(dt, Utc.ymd(2014, 7, 8).and_hms_nano(9, 10, 11, 12_000_000));

// dynamic verification
assert_eq!(Utc.ymd_opt(2014, 7, 8).and_hms_opt(21, 15, 33),
           LocalResult::Single(Utc.ymd(2014, 7, 8).and_hms(21, 15, 33)));
assert_eq!(Utc.ymd_opt(2014, 7, 8).and_hms_opt(80, 15, 33), LocalResult::None);
assert_eq!(Utc.ymd_opt(2014, 7, 38).and_hms_opt(21, 15, 33), LocalResult::None);

// other time zone objects can be used to construct a local datetime.
// obviously, `local_dt` is normally different from `dt`, but `fixed_dt` should be identical.
let local_dt = Local.ymd(2014, 7, 8).and_hms_milli(9, 10, 11, 12);
let fixed_dt = FixedOffset::east(9 * 3600).ymd(2014, 7, 8).and_hms_milli(18, 10, 11, 12);
assert_eq!(dt, fixed_dt);

Various properties are available to the date and time, and can be altered individually. Most of them are defined in the traits Datelike and Timelike which you should use before. Addition and subtraction is also supported. The following illustrates most supported operations to the date and time:

use chrono::prelude::*;
use chrono::Duration;

// assume this returned `2014-11-28T21:45:59.324310806+09:00`:
let dt = FixedOffset::east(9*3600).ymd(2014, 11, 28).and_hms_nano(21, 45, 59, 324310806);

// property accessors
assert_eq!((dt.year(), dt.month(), dt.day()), (2014, 11, 28));
assert_eq!((dt.month0(), dt.day0()), (10, 27)); // for unfortunate souls
assert_eq!((dt.hour(), dt.minute(), dt.second()), (21, 45, 59));
assert_eq!(dt.weekday(), Weekday::Fri);
assert_eq!(dt.weekday().number_from_monday(), 5); // Mon=1, ..., Sun=7
assert_eq!(dt.ordinal(), 332); // the day of year
assert_eq!(dt.num_days_from_ce(), 735565); // the number of days from and including Jan 1, 1

// time zone accessor and manipulation
assert_eq!(dt.offset().fix().local_minus_utc(), 9 * 3600);
assert_eq!(dt.timezone(), FixedOffset::east(9 * 3600));
assert_eq!(dt.with_timezone(&Utc), Utc.ymd(2014, 11, 28).and_hms_nano(12, 45, 59, 324310806));

// a sample of property manipulations (validates dynamically)
assert_eq!(dt.with_day(29).unwrap().weekday(), Weekday::Sat); // 2014-11-29 is Saturday
assert_eq!(dt.with_day(32), None);
assert_eq!(dt.with_year(-300).unwrap().num_days_from_ce(), -109606); // November 29, 301 BCE

// arithmetic operations
let dt1 = Utc.ymd(2014, 11, 14).and_hms(8, 9, 10);
let dt2 = Utc.ymd(2014, 11, 14).and_hms(10, 9, 8);
assert_eq!(dt1.signed_duration_since(dt2), Duration::seconds(-2 * 3600 + 2));
assert_eq!(dt2.signed_duration_since(dt1), Duration::seconds(2 * 3600 - 2));
assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) + Duration::seconds(1_000_000_000),
           Utc.ymd(2001, 9, 9).and_hms(1, 46, 40));
assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) - Duration::seconds(1_000_000_000),
           Utc.ymd(1938, 4, 24).and_hms(22, 13, 20));

Formatting and Parsing

Formatting is done via the format method, which format is equivalent to the familiar strftime format.

See format::strftime documentation for full syntax and list of specifiers.

The default to_string method and {:?} specifier also give a reasonable representation. Chrono also provides to_rfc2822 and to_rfc3339 methods for well-known formats.

Chrono now also provides date formatting in almost any language without the help of an additional C library. This functionality is under the feature unstable-locales:

chrono = { version = "0.4", features = ["unstable-locales"] }

The unstable-locales feature requires and implies at least the alloc feature.

use chrono::prelude::*;

let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), "2014-11-28 12:00:09");
assert_eq!(dt.format("%a %b %e %T %Y").to_string(), "Fri Nov 28 12:00:09 2014");
assert_eq!(dt.format_localized("%A %e %B %Y, %T", Locale::fr_BE).to_string(), "vendredi 28 novembre 2014, 12:00:09");

assert_eq!(dt.format("%a %b %e %T %Y").to_string(), dt.format("%c").to_string());
assert_eq!(dt.to_string(), "2014-11-28 12:00:09 UTC");
assert_eq!(dt.to_rfc2822(), "Fri, 28 Nov 2014 12:00:09 +0000");
assert_eq!(dt.to_rfc3339(), "2014-11-28T12:00:09+00:00");
assert_eq!(format!("{:?}", dt), "2014-11-28T12:00:09Z");

// Note that milli/nanoseconds are only printed if they are non-zero
let dt_nano = Utc.ymd(2014, 11, 28).and_hms_nano(12, 0, 9, 1);
assert_eq!(format!("{:?}", dt_nano), "2014-11-28T12:00:09.000000001Z");

Parsing can be done with three methods:

  1. The standard FromStr trait (and parse method on a string) can be used for parsing DateTime<FixedOffset>, DateTime<Utc> and DateTime<Local> values. This parses what the {:?} (std::fmt::Debug) format specifier prints, and requires the offset to be present.

  2. DateTime::parse_from_str parses a date and time with offsets and returns DateTime<FixedOffset>. This should be used when the offset is a part of input and the caller cannot guess that. It cannot be used when the offset can be missing. DateTime::parse_from_rfc2822 and DateTime::parse_from_rfc3339 are similar but for well-known formats.

  3. Offset::datetime_from_str is similar but returns DateTime of given offset. When the explicit offset is missing from the input, it simply uses given offset. It issues an error when the input contains an explicit offset different from the current offset.

More detailed control over the parsing process is available via format module.

use chrono::prelude::*;

let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
let fixed_dt = dt.with_timezone(&FixedOffset::east(9*3600));

// method 1
assert_eq!("2014-11-28T12:00:09Z".parse::<DateTime<Utc>>(), Ok(dt.clone()));
assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<Utc>>(), Ok(dt.clone()));
assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<FixedOffset>>(), Ok(fixed_dt.clone()));

// method 2
assert_eq!(DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z"),
           Ok(fixed_dt.clone()));
assert_eq!(DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900"),
           Ok(fixed_dt.clone()));
assert_eq!(DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00"), Ok(fixed_dt.clone()));

// method 3
assert_eq!(Utc.datetime_from_str("2014-11-28 12:00:09", "%Y-%m-%d %H:%M:%S"), Ok(dt.clone()));
assert_eq!(Utc.datetime_from_str("Fri Nov 28 12:00:09 2014", "%a %b %e %T %Y"), Ok(dt.clone()));

// oops, the year is missing!
assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T %Y").is_err());
// oops, the format string does not include the year at all!
assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T").is_err());
// oops, the weekday is incorrect!
assert!(Utc.datetime_from_str("Sat Nov 28 12:00:09 2014", "%a %b %e %T %Y").is_err());

Again : See format::strftime documentation for full syntax and list of specifiers.

Conversion from and to EPOCH timestamps

Use Utc.timestamp(seconds, nanoseconds) to construct a DateTime<Utc> from a UNIX timestamp (seconds, nanoseconds that passed since January 1st 1970).

Use DateTime.timestamp to get the timestamp (in seconds) from a DateTime. Additionally, you can use DateTime.timestamp_subsec_nanos to get the number of additional number of nanoseconds.

// We need the trait in scope to use Utc::timestamp().
use chrono::{DateTime, TimeZone, Utc};

// Construct a datetime from epoch:
let dt = Utc.timestamp(1_500_000_000, 0);
assert_eq!(dt.to_rfc2822(), "Fri, 14 Jul 2017 02:40:00 +0000");

// Get epoch value from a datetime:
let dt = DateTime::parse_from_rfc2822("Fri, 14 Jul 2017 02:40:00 +0000").unwrap();
assert_eq!(dt.timestamp(), 1_500_000_000);

Individual date

Chrono also provides an individual date type (Date). It also has time zones attached, and have to be constructed via time zones. Most operations available to DateTime are also available to Date whenever appropriate.

use chrono::prelude::*;
use chrono::offset::LocalResult;

assert_eq!(Utc::today(), Utc::now().date());
assert_eq!(Local::today(), Local::now().date());

assert_eq!(Utc.ymd(2014, 11, 28).weekday(), Weekday::Fri);
assert_eq!(Utc.ymd_opt(2014, 11, 31), LocalResult::None);
assert_eq!(Utc.ymd(2014, 11, 28).and_hms_milli(7, 8, 9, 10).format("%H%M%S").to_string(),
           "070809");

There is no timezone-aware Time due to the lack of usefulness and also the complexity.

DateTime has date method which returns a Date which represents its date component. There is also a time method, which simply returns a naive local time described below.

Naive date and time

Chrono provides naive counterparts to Date, (non-existent) Time and DateTime as NaiveDate, NaiveTime and NaiveDateTime respectively.

They have almost equivalent interfaces as their timezone-aware twins, but are not associated to time zones obviously and can be quite low-level. They are mostly useful for building blocks for higher-level types.

Timezone-aware DateTime and Date types have two methods returning naive versions: naive_local returns a view to the naive local time, and naive_utc returns a view to the naive UTC time.

Limitations

Only proleptic Gregorian calendar (i.e. extended to support older dates) is supported. Be very careful if you really have to deal with pre-20C dates, they can be in Julian or others.

Date types are limited in about +/- 262,000 years from the common epoch. Time types are limited in the nanosecond accuracy.

Leap seconds are supported in the representation but Chrono doesn't try to make use of them. (The main reason is that leap seconds are not really predictable.) Almost every operation over the possible leap seconds will ignore them. Consider using NaiveDateTime with the implicit TAI (International Atomic Time) scale if you want.

Chrono inherently does not support an inaccurate or partial date and time representation. Any operation that can be ambiguous will return None in such cases. For example, "a month later" of 2014-01-30 is not well-defined and consequently Utc.ymd(2014, 1, 30).with_month(2) returns None.

Non ISO week handling is not yet supported. For now you can use the chrono_ext crate (sources).

Advanced time zone handling is not yet supported. For now you can try the Chrono-tz crate instead.

Comments
  • Bump time to 0.3

    Bump time to 0.3

    Fixes https://github.com/chronotope/chrono/issues/553, https://github.com/chronotope/chrono/pull/567

    This updates the time dependency to 0.3. The crate has been refactored to follow time API changes.

    This includes not-yet-merged changes made in https://github.com/chronotope/chrono/pull/567.

    Tasks:

    • [x] Bump time to 0.3 when released (see https://github.com/time-rs/time/issues/248)
    • [x] Refactor codebase for time API changes
    • [x] Fix test naive::date::tests::test_date_add (failing case)
    • [x] Fix test naive::datetime::tests::test_datetime_add (failing case)
    • [x] Have you added yourself and the change to the changelog? (Don't worry about adding the PR number)
    opened by timvisee 98
  • The call to `localtime_r` may be unsound

    The call to `localtime_r` may be unsound

    I found that getenv and setenv in libc are not thread-safe [1], and most impl of localtime_r in libc directly call getenv [2]. This means that localtime_r may have data race with setenv.

    In order to ensure soundness of setenv, libstd add a lock to it [1], but this means that using getenv without libstd will be unsound.

    This problem is not easy to reproduce on glibc, because glibc's localtime_r caches timezone. but using musl can easily reproduce it.

    1. https://github.com/rust-lang/rust/pull/24741
    2. https://github.com/aosp-mirror/platform_bionic/blob/master/libc/tzcode/localtime.c#L1321 and https://git.musl-libc.org/cgit/musl/tree/src/time/__tz.c#n127

    POC: https://gist.github.com/quininer/2063c31b0bc1753989122e782b182bea

    opened by quininer 42
  • Add pyo3 integration

    Add pyo3 integration

    Some parts taken from https://github.com/kangalioo/pyo3-chrono

    Note, I will continue working on this in few more days, I have something I wanted to experiment in the meantime.

    cc @kangalioo

    Implemented

    • [x] PyDate <-> NaiveDate
    • [x] PyTime <-> NaiveTime
    • [x] PyDateTime <-> NaiveDateTime
    • [x] PyDelta <-> Duration (only implemented for oldtime feature)
    • [x] ~~PyDate <-> Date~~ (may confuse people since PyDate does not have timezone)
    • [x] PyTzInfo <-> Utc
    • [x] PyTzInfo <-> FixedOffset
    • [x] PyDateTime <-> DateTime

    Thanks for contributing to chrono!

    • [x] Have you added yourself and the change to the changelog? (Don't worry about adding the PR number)
    • [ ] If this pull request fixes a bug, does it add a test that verifies that we can't reintroduce it?
    opened by pickfire 32
  • Locales

    Locales

    Closes #199 Closes #153

    I made a pure Rust lib without any dependency that has the locales from glibc. It does not depend on glibc. It's using the locale data files from glibc.

    % This file is part of the GNU C Library and contains locale data.
    % The Free Software Foundation does not claim any copyright interest
    % in the locale data contained in this file.  The foregoing does not
    % affect the license of the GNU C Library as a whole.  It does not
    % exempt you from the conditions of the license if your use would
    % otherwise be governed by that license.
    

    I contacted the FSF and they seem to allow the use of these data:

    In short, we believe these files aren't copyrightable; for more background, please check https://sourceware.org/ml/libc-locales/2013-q1/msg00048.html

    -- I am not a lawyer, this is not a legal advice.

    The PR is a draft, I'm waiting for your feedback before finishing it.

    opened by cecton 27
  • Use core::time::Duration via an enum

    Use core::time::Duration via an enum

    Setting this up so it can run through the CI for now, this shouldn't be merged until at least version 0.5, or possibly never.

    This is one option to use core::time::Duration in chrono's duration. The main change here is to remove the oldtime modules, and rename the Duration type to SignedDuration which can now be infallibly converted both ways with core::time::Duration (albeit via an absolute value when going to core::time::Duration)

    pub enum SignedDuration {
        /// A duration heading in forwards in time
        Forwards(Duration),
        /// A duration heading in backwards in time
        Backwards(Duration),
    }
    
    API-incompatible 
    opened by esheppa 24
  • CVE-2020-26235 advisory for time 0.1 dependency

    CVE-2020-26235 advisory for time 0.1 dependency

    Please update time dependency.

    Inverse Dependency graph time 0.1.44 (registry+https://github.com/rust-lang/crates.io-index) └── chrono 0.4.19 (registry+https://github.com/rust-lang/crates.io-index)

    opened by acim 24
  •  Add initial support for the `wasm32` arch

    Add initial support for the `wasm32` arch

    Building on PR #286, this PR adds initial support to chrono for the wasm32 architecture. Specifically, it adds wasm32-compatible versions of the Local::now() and Utc::now() constructors.

    EDIT: merging this would allow this issue to be closed as well.

    opened by jjpe 23
  • supported timezone syntax for DateTime from string

    supported timezone syntax for DateTime from string

    I'm trying to accommodate the default timezone syntax returned from postgresql. It seems to provide an abbreviated form that chrono may not support-- it omits 00 minutes. Is there support for this in Chrono?

    http://play.integer32.com/?gist=b6394d764deb6a4bcf7b1b5ebd038969&version=stable

    extern crate chrono;
    use chrono::prelude::*;
    use chrono::DateTime;
    
    fn main() {
        let dt = "2018-02-06 11:17:09.534889-05";
        let test = DateTime::parse_from_str(dt, "%Y-%m-%d %H:%M:%S%.6f-%z");
        println!("{:?}", test);                                        
    }
    
    
    bug D-medium 
    opened by Dowwie 23
  • Create `add_months()` method on `NaiveDate`

    Create `add_months()` method on `NaiveDate`

    The Apache arrow-datafusion project is a query engine that supports doing date math with arrow primitives like IntervalYearMonth, which despite being a common part of SQL standards, adding months to a NaiveDate was surprisingly non-trivial to perform correctly.

    Support is being added to arrow-datafusion in this PR, but it seemed like logic like this might best make it's home in the chrono crate, so that others don't have to re-implement this logic. A quick search of issues reveals some demand:

    • https://github.com/chronotope/chrono/issues/474
    • https://github.com/chronotope/chrono/issues/290

    Unfortunately, I realize there is no Duration::Month because it doesn't represent a fixed duration in time, so hopefully this is an acceptable compromise. If not, I defer to the maintainers on the best way to implement such functionality.

    opened by avantgardnerio 22
  • Make ParseErrorKind public and available through ParseError::kind()

    Make ParseErrorKind public and available through ParseError::kind()

    ParseErrorKind has also been made #[non_exhaustive] to avoid committing to only the current set of error kinds, i.e. so that it can be expanded as needed without an SemVer-breaking change.

    Thanks for contributing to chrono!

    • [x] Have you added yourself and the change to the changelog? (Don't worry about adding the PR number)
    • [x] If this pull request fixes a bug, does it add a test that verifies that we can't reintroduce it?

    Fixes #319

    opened by sbrocket 22
  • Better usage of SemVer

    Better usage of SemVer

    The upgrade from 0.3.0 to 0.3.1 broke several of my projects because the dependency on serde 0.9 to 1.0 caused API incompatibilities. It would be nice if you guys were more mindful of this in the future.

    meta 
    opened by heartsucker 22
  • Years type implementation

    Years type implementation

    I started a simple implementation that I intend to add proper add checks once the problem is actually solved.

    I implemented simples tests too, but there is still a lot to do. I'm currently opening the PR so discussions about the implementation can occur here and you guys can follow the progress. I believe this is semver compatible since I'm only adding a new type so I targeted the 0.4.x branch, hopefully, this type will make it into that version.

    I already applied the recommendations @esheppa made in this comment on issue #416

    opened by Rafael-Conde 1
  • Documentation of commit style in PRs

    Documentation of commit style in PRs

    As we are using the "Rebase and Merge" strategy rather than the "Squash and Merge" strategy to merge PRs, we require fixes to be done in the underlying commits rather than in new commits during PR review. We should document this and have some recommendations of how to achieve this, something along the lines of usage of:

    Redoing commits

    • git rebase -i HEAD~n and using edit, squash and exec Splitting commits
    • git reset to set up the state for subsequently using git add -i
    • git add -i and using the patch mode to stage some but not all of a given diff for a file

    With the understanding that there are many ways to achieve the same result and this is just one of the possible ways

    opened by esheppa 0
  • Use std duration with NaiveTime

    Use std duration with NaiveTime

    • Add overflowing_add_opt and overflowing_sub_opt, similar to the existing overflowing_add_signed/overflowing_sub_signed. The implementations are a bit more complex as as they can no longer use negation. There may be opportunity for more shared code between overflowing_add_opt and overflowing_sub_opt
    • Add abs_diff and duration_since which are similar to signed_duration_since. Implementation of abs_diff is more verbose as it explicitly states all possible cases
    • Add and Sub for NaiveTime.
    • offset/fixed.rs has some impls updated to use the new APIs
    • Change NaiveDateTime impls to use the new API internally (they are now more verbose as have to handle positive and negative cases. These functions will be deprecated in 0.5 anyway (and could be in a future PR which implements similar functions using core::time::Duration)
    opened by esheppa 0
  • Confusing documentation surrounding chrono::naive::Days

    Confusing documentation surrounding chrono::naive::Days

    The documentation for chrono::naive::Days::new says it constructs a new Days from a number of months. Not only is this confusing, it is also incorrect, as a quick test shows that using it with checked_add_days only adds one day.

    Reference: https://github.com/chronotope/chrono/blob/2aa222112999df57d063b60510f02cc0e7ee4e7f/src/naive/date.rs#L127

    opened by Areskiko 0
  • Add a feature to extend the supported range of dates

    Add a feature to extend the supported range of dates

    At boa (A Javascript interpreter) we're using chrono to handle the Javascript Date builtin; we mainly use it to easily create, parse and format local and UTC datetimes. However, we discovered that several tests were failing because of the supported range of dates by chrono. The README specifies:

    Date types are limited in about +/- 262,000 years from the common epoch.

    While the ECMAScript spec mentions:

    The smaller range supported by a time value as specified in this section is approximately -273,790 to 273,790 years relative to 1970.

    chrono's supported range is smaller than the range specified by the spec.

    The time crate has a feature (large-dates) to extend the allowed range of dates, so we would be very glad to see a similar feature in chrono that extended its supported range.

    Thanks!

    opened by jedel1043 1
Releases(v0.4.23)
  • v0.4.23(Nov 12, 2022)

    0.4.23 is the next 0.4 release of the popular chrono date and time library for Rust. After the 0.4.20-0.4.22 series that brought chrono back to life after a long hiatus, development has been fairly quiet, allowing us to start planning changes for the 0.5.0 release. As such, we've started deprecating some APIs that are likely to be removed in 0.5. If you have any feedback on these changes, please let us know in the issue tracker!

    Deprecations

    • Deprecate methods that have an _opt() alternative (#827)
    • Deprecate usage of the Date<Tz> type (#851)

    Features

    • Optimize RFC 3339 (and RFC 2822) encoding (#844, thanks to @conradludgate)
    • Addition and subtraction with the Days type (#784)
    • Add NaiveDateTime::from_timestamp_millis(_opt) (#818, thanks to @Pscheidl -- backported in #823)
    • Allow for changing TZ variable and cache it for Local timezone (#853)
    • Add optional support for the arbitrary::Arbitrary trait (#849, thanks to @greyblake and @asayers)

    Fixes

    • Support tzdb location on AIX (#826)
    • Fix warnings in documentation (#847)

    On behalf of @esheppa and @djc, thanks to all contributors!

    Source code(tar.gz)
    Source code(zip)
  • v0.4.22(Aug 13, 2022)

    Unfortunately the introduction of the iana-time-zone dependency in 0.4.21 caused some new regressions with lesser known platforms. This release fixes all of the issues we've encountered, improving the situation on some WebAssembly targets, SGX and on macOS/iOS. We've improved our CI setup to hopefully catch more of these issues before release in the future.

    • Make wasm-bindgen optional on wasm32-unknown-unknown target (#771)
    • Avoid iana-time-zone dependency on x86_64-fortanix-unknown-sgx (#767, thanks to @trevor-crypto)
    • Update iana-time-zone version to 0.1.44 to avoid cyclic dependencies (#773, thanks to @Kijewski for the upstream PRs)
    • Clarify documentation about year range in formatting/parsing (#765)
    Source code(tar.gz)
    Source code(zip)
  • v0.4.21(Aug 9, 2022)

    0.4.21 is a bugfix release that mainly fixes one regression from 0.4.20:

    • Fall back to UTC in case no timezone is found. Unfortunately this is a regression from the changes we made in 0.4.20 where we now parse the timezone database ourselves. Before 0.4.20, TimeZone::now() fell back to UTC in the case it could not find the current timezone, but the new implementation panicked in that case.
    • Correctly detect timezone on Android (also #756). Android does have the timezone database installed, but it's in a different path, and it does not use /etc/localtime to keep track of the current timezone. Instead we now use the iana-time-zone crate as a dependency, since it already has quite a bit of logic for finding the current timezone on a host of platforms.

    Additionally, there is a documentation fix that reverts an incorrect guarantee:

    • Document that %Y can have a negative value, both in formatting and in parsing (#760, thanks to @alex)
    Source code(tar.gz)
    Source code(zip)
  • v0.4.20(Aug 4, 2022)

    chrono is a date and time library for Rust and 0.4.20 is the first chrono release since Sep 2020. There has been a long hiatus since the previous maintainer was no longer able to spend much time on the crate; thanks to @quodlibetor for their stewardship of the chrono crate for many years! The new maintainers are @djc and @esheppa. Our first priority has been fixing the soundness issues with calls to localtime_r() as first reported in #499 and the RUSTSEC-2020-0159 advisory. In order to do this we adapted code from the tz-rs crate maintained by @x-hgg-x for use within chrono -- thanks for working on that! With the new implementation, chrono uses safe Rust code to parse the timezone data files on Unix platforms directly instead of relying on libc.

    Due to compatibility reasons, this release does not yet remove the time 0.1 dependency, though chrono 0.4.20 does not depend on the vulnerable parts of the time 0.1.x versions. In a future 0.5 release, we will remove the time dependency.

    The minimum supported Rust version for 0.4.20 is 1.32.0, which is intentionally still quite conservative. If you are using chrono 0.4 with a Rust version older than 1.52, we'd like to hear from you since we'd like to further modernize the code base to ease maintenance.

    Fixes

    • Fix unsound call to localtime_r() by parsing timezone files in Rust on Unix (#677 and #728)
    • Allow RFC 2822 parser to deal with comments (#733 then #737, thanks to @Finomnis)
    • Avoid panicking during parsing (#686, thanks to @botahamec)
    • Avoid panics when rounding durations (#659, thanks to @ARBaart)
    • Fix Duration::abs() behavior in case of negative durations with nanoseconds (#734, thanks to @abreis)

    Additions

    • Make ParserErrorKind public and available through ParseError::kind() (#588, thanks to @sbrocket)
    • Expose associated MIN and MAX const values in favor of free-standing consts (#726)
    • Add (optional) support for rkyv (#644 and #701, thanks to @dovahcrow)
    • Support month-based calculations against NaiveDate (#732 with follow up in #752, thanks to @avantgardnerio)
    • Add NaiveWeek type to facilitate week-based calculations (#666, thanks to @sestrella)
    • Add NaiveDateTime::and_local_timezone() method (#711, thanks to @botahamec)
    • Add DateTime::from_local() method (#572, thanks to @retrhelo)
    • Extend serde integration for NaiveDateTime (#664, thanks to @nickelc)
    • Implement DoubleEndedIterator for NaiveDateDaysIterator/NaiveDateWeeksIterator (#697, thanks to @teobouvard)
    • Implement std::iter::Sum for Duration (#522, thanks to @jakevossen5)
    • Add years_since() method to DateTime/Date (#557 then #707, thanks to @yozhgoor)
    • Implement AddAssign/SubAssign for DateTime/Date (#698, thanks to @MrGunflame)
    • Fix imports on WASM targets (#672, thanks to @danielalvsaaker)
    • Implement std::error::Error for ParseWeekdayError (#745)

    Non-functional improvements

    • Improve CI to better exercise WASM targets (#662, thanks to @AmateurECE)
    • More WASM testing improvements, enable dependencies by default (#746)
    • Fix compiling for wasm32-unknown-emscripten target (#568, thanks to @orion78fr)
    • Use stub implementation for anything not unix and not windows (#593, thanks to @yu-re-ka)
    • Remove now unused libc dependency (#710, thanks to @metent)
    • Clean up some clippy warnings (#721, thanks to @botahamec)
    • Clarify documentation for Utc::now() (#647, thanks to @ModProg)
    • Clarify documentation for DateTime::with_timezone() (#747, thanks to @kevincox)
    • Improve examples for naive serde integration (#616, thanks to @nickelc)
    • Clean up extern crate statements and outdated comments (#665, thanks to @nickelc)
    • Fix typo in deprecation notice (#744, thanks to @Mike-Dax)
    • Fix some typos in documentation (#680 and #695, thanks to @cuishuang and @fxredeemer)
    • Implement caching for CI (#609, thanks to @Milo123459)
    Source code(tar.gz)
    Source code(zip)
  • v0.4.20-rc.1(Jul 26, 2022)

    0.4.20 is the first chrono release since Sep 2020. There has been a long hiatus since the previous maintainer was no longer able to spend much time on the crate; thanks to @quodlibetor for their stewardship of the chrono crate for many years! The new maintainers are @djc and @esheppa. Our first priority has been fixing the soundness issues with calls to localtime_r() as first reported in #499 and the RUSTSEC-2020-0159 advisory. In order to do this we adapted code from the tz-rs crate maintained by @x-hgg-x for use within chrono -- thanks for working on that! With the new implementation, chrono uses safe Rust code to parse the timezone data files on Unix platforms directly instead of relying on libc.

    Due to compatibility reasons, this release does not yet remove the time 0.1 dependency, though chrono 0.4.20 does not depend on the vulnerable parts of the time 0.1.x versions. In a future 0.5 release, we will remove the time dependency.

    The minimum supported Rust version for 0.4.20 is 1.32.0, which is intentionally still quite conservative. If you are using chrono 0.4 with a Rust version older than 1.52, we'd like to hear from you since we'd like to further modernize the code base to ease maintenance.

    Fixes

    • Fix unsound call to localtime_r() by parsing timezone files in Rust on Unix (#677 and #728)
    • Allow RFC 2822 parser to deal with comments (#733 then #737, thanks to @Finomnis)
    • Avoid panicking during parsing (#686, thanks to @botahamec)
    • Avoid panics when rounding durations (#659, thanks to @ARBaart)
    • Fix Duration::abs() behavior in case of negative durations with nanoseconds (#734, thanks to @abreis)

    Additions

    • Make ParserErrorKind public and available through ParseError::kind() (#588, thanks to @sbrocket)
    • Expose associated MIN and MAX const values in favor of free-standing consts (#726)
    • Add (optional) support for rkyv (#644 and #701, thanks to @dovahcrow)
    • Support month-based calculations against NaiveDate (#732 with follow up in #752, thanks to @avantgardnerio)
    • Add NaiveWeek type to facilitate week-based calculations (#666, thanks to @sestrella)
    • Add NaiveDateTime::and_local_timezone() method (#711, thanks to @botahamec)
    • Add DateTime::from_local() method (#572, thanks to @retrhelo)
    • Extend serde integration for NaiveDateTime (#664, thanks to @nickelc)
    • Implement DoubleEndedIterator for NaiveDateDaysIterator/NaiveDateWeeksIterator (#697, thanks to @teobouvard)
    • Implement std::iter::Sum for Duration (#522, thanks to @jakevossen5)
    • Add years_since() method to DateTime/Date (#557 then #707, thanks to @yozhgoor)
    • Implement AddAssign/SubAssign for DateTime/Date (#698, thanks to @MrGunflame)
    • Fix imports on WASM targets (#672, thanks to @danielalvsaaker)
    • Implement std::error::Error for ParseWeekdayError (#745, after rc.1)

    Non-functional improvements

    • Improve CI to better exercise WASM targets (#662, thanks to @AmateurECE)
    • More WASM testing improvements, enable dependencies by default (#746)
    • Fix compiling for wasm32-unknown-emscripten target (#568, thanks to @orion78fr)
    • Use stub implementation for anything not unix and not windows (#593, thanks to @yu-re-ka)
    • Remove now unused libc dependency (#710, thanks to @metent)
    • Clean up some clippy warnings (#721, thanks to @botahamec)
    • Clarify documentation for Utc::now() (#647, thanks to @ModProg)
    • Clarify documentation for DateTime::with_timezone() (#747, thanks to @kevincox)
    • Improve examples for naive serde integration (#616, thanks to @nickelc)
    • Clean up extern crate statements and outdated comments (#665, thanks to @nickelc)
    • Fix typo in deprecation notice (#744, thanks to @Mike-Dax)
    • Fix some typos in documentation (#680 and #695, thanks to @cuishuang and @fxredeemer)
    • Implement caching for CI (#609, thanks to @Milo123459)
    Source code(tar.gz)
    Source code(zip)
  • v0.4.19(Sep 30, 2020)

  • v0.4.18(Sep 26, 2020)

  • v0.4.17(Sep 26, 2020)

  • v0.4.16(Sep 25, 2020)

  • v0.4.15(Sep 25, 2020)

Owner
Chronotope
Home for Chrono, a Rust date/time library
Chronotope
rsdate connects to an ntp server, printing the returned time and/or sets the system clock.

?? ?? rsdate rsdate connects to an ntp server, printing the returned time and/or sets the system clock.

Wesley Moore 4 Nov 2, 2022
A simple and fun way to view the time!

Concentric Time A simple and fun way to view the time! Screenshots Dark mode Light mode Dev This project uses Dioxus (a Rust-Wasm framework) and does

Parker McMullin 9 Oct 23, 2022
Time series anomaly detection for Rust

AnomalyDetection.rs Time series AnomalyDetection for Rust Learn how it works Installation Add this line to your application’s Cargo.toml under [depend

Andrew Kane 6 Nov 21, 2022
A set of tools for generating signed exchanges at serve time.

sxg-rs sxg-rs is a set of tools for generating signed exchanges at serve time: cloudflare_worker runs on Cloudflare Workers. fastly_compute runs on Fa

Google 63 Nov 14, 2022
datez: convert a time into several timezones

datez: convert a time into several timezones In July, when it is 16:00 in Canberra, what time is it in Caracas, and where I am in Cambridge? $ datez 2

Tony Finch 7 Nov 17, 2021
Get unix time (nanoseconds) in blazing low latency with high precision

RTSC Get unix time (nanoseconds) in blazing low latency with high precision. About 5xx faster than SystemTime::now(). Performance OS CPU benchmark rts

Ⅲx 8 Jul 14, 2022
Generate perfect code headers every time.

Generate perfect code headers every time.

t11s 102 Nov 23, 2022
eos is a datetime library for Rust, aimed at being robust, simple, and easy to use

eos eos is a datetime library for Rust, aimed at being robust, simple, and easy to use. eos is made with the assumption of operating under a proleptic

Danny 46 Nov 18, 2022
A pure Rust reimplementation of libc functions localtime, gmtime and mktime.

tz-rs A pure Rust reimplementation of libc functions localtime, gmtime and mktime. This crate allows to convert between a Unix timestamp and a calenda

null 155 Sep 16, 2022
This crate provides high-performance formatting and parsing routines for ISO8061 timestamps

ISO8061 Timestamp This crate provides high-performance formatting and parsing routines for ISO8061 timestamps, primarily focused on UTC values but wit

Lantern 4 Sep 21, 2022
The implementation of the Persian (Solar Hijri) Calendar in Rust

Rust Persian Calendar Rust Persian Calendar v0.1.1 provides functionality for conversion among Persian (Solar Hijri) and Gregorian calendars. A Julian

Navid 27 Mar 5, 2022
Cocom - NTP client written in Rust

Cocom is an implementation of the NTP-protocol, to receive the time from NTP-server. The client does not necessarily need arguments.

Maximilian Sonnenburg 6 Nov 26, 2021
Date and time library for Rust. Feature rich, lightweight and easy-to-use.

Astrolabe Date and time library for Rust. Feature rich, lightweight and easy-to-use. Documentation | Github | Crate Example Status Astrolabe is curren

Jasmin 2 Sep 2, 2022
Date and time library for Rust

Chrono: Date and Time for Rust It aims to be a feature-complete superset of the time library. In particular, Chrono strictly adheres to ISO 8601. Chro

Chronotope 2.4k Nov 25, 2022
Fast and simple datetime, date, time and duration parsing for rust.

speedate Fast and simple datetime, date, time and duration parsing for rust. speedate is a lax† RFC 3339 date and time parser, in other words, it pars

Samuel Colvin 43 Nov 25, 2022
A Yocto setup and management tool that helps you keep your environment up-to-date and in-sync with your team

yb (Yocto Buddy) yb is designed to make it easy to setup and (perhaps more importantly) keep Yocto environments up-to-date and in-sync with your team.

null 13 Oct 31, 2022
Easy, Simple, Clean. Making status bars reliable and up-to-date.

Simple Status Easy, Simple, Clean. Making status bars reliable and up-to-date. Installation Compiling simple_status yourself doesn't require much. Ins

James Butcher 5 Aug 1, 2022
httm prints the size, date and corresponding locations of available unique versions of files residing on ZFS snapshots

httm prints the size, date and corresponding locations of available unique versions of files residing on ZFS snapshots, as well as allowing their interactive viewing and restoration.

null 786 Nov 26, 2022
Rust TLS/SSL certificate expiration date from command-line checker

Rust TLS/SSL certificate expiration date from command-line checker

Jose Bovet Derpich 9 Nov 9, 2022
A cargo subcommand for displaying when Rust dependencies are out of date

cargo-outdated Linux: A cargo subcommand for displaying when Rust dependencies are out of date About cargo-outdated is for displaying when dependencie

Kevin K. 905 Nov 20, 2022