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
  • Replace `winapi` with `windows-sys`

    Replace `winapi` with `windows-sys`

    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?
    API-incompatible 
    opened by hotate29 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
  • Resetting time to 00:00:00.0

    Resetting time to 00:00:00.0

    It takes too many lines to do a simple and commonly used (at least in my case) operation:

    let x = dt.with_hour(0).unwrap().with_minute(0).unwrap().with_second(0).unwrap();
    

    Is there a simpler way of achieving the same?

    if not, would you consider a PR to do a reset like that in a single step? E.g.

    let x = dt.reset_time();
    
    opened by rimutaka 1
  • Allow guaranteed-no-panic conversion from NaiveDate to DateTime

    Allow guaranteed-no-panic conversion from NaiveDate to DateTime

    Hello people,

    First, thank you for making chrono! It's very helpful to write code that (hopefully) will work on any timezone.

    However, this "make it work on any timezone" makes me scared about doing some stuff that still sounds really reasonable.

    So I'm opening this PR to kill two birds with one stone: asking my question ("how can I make a DateTime at the first second of a day"), and providing an easy way for others to know and use the answer.

    Basically, I'm wondering whether the implementation of this PR is correct. Is it possible for eg. a summer time change change to happen across midnight?

    If the implementation of this PR is always correct, then I think it should land, because otherwise writing the code as an end-user of the library does not make it obvious that it is actually panic-free. And this leads to convoluted ways to work around it. For instance my current solution is I already have a DateTime, and add 86400-its number of seconds since the beginning of the day; and that gives me a very-approximated-during-summer-time-changes but guaranteed no-panic solution.

    If the implementation of this PR is incorrect, how would you go about solving the problem at hand, and do you think it would be possible to integrate it into chrono itself?

    Either way, have a good end-of-year holiday!

    opened by Ekleog 1
  • Add support for parsing JSON timestamps from strings.

    Add support for parsing JSON timestamps from strings.

    This change adds support for parsing string as (numeric) timestamps.

    I had a look at the tests but was not sure where I should put the test for this feature, as the current logic to run tests is calling datetime::test_decodable_json which does not seem to be exercising the visitor path? Let me know where I should put them and I'll add the tests.

    opened by rayhaanj 0
  • Implement generic assign operations for various types

    Implement generic assign operations for various types

    Includes:

    • oldtime::Duration
    • datetime::DateTime
    • naive::date::NaiveDate
    • naive::datetime::NaiveDateTime
    • naive::time::NaiveTime

    Did not implement it for date::Date. This is because Add expects to be passed the owned object, but AddAssign only has access to a mutable reference. Since Date doesn't implement Copy, that makes it impossible to generically and safely implement AddAssign using Add without cloning. It might be possible with unsafe code, but that's probably over the top. date::Date is deprecated anyways.

    opened by yottalogical 0
  • use #[non_exhaustive]

    use #[non_exhaustive]

    Thanks for contributing to chrono!

    If your feature is semver-compatible, please target the 0.4.x branch; the main branch will be used for 0.5.0 development going forward.

    Please consider adding a test to ensure your bug fix/feature will not break in the future.

    MSRV has been bumped at https://github.com/chronotope/chrono/commit/95532dbc99315ee17597e1fb43b783b94f2e9952, and #[non_exhaustive] is stabilized in 1.40. We can remove the tricks now.

    opened by TennyZhuang 0
  • Create a `NaiveTime` from 12-hour format

    Create a `NaiveTime` from 12-hour format

    Timelike has a hour_12 method, I think it'd be nice to have this in reverse, I'm thinking it should be like NaiveTime::from_hms_12(h, m, s, AmPm::Am), thoughts?

    opened by laralove143 2
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 3 Dec 31, 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 64 Dec 26, 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 111 Dec 28, 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 51 Dec 19, 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 159 Jan 2, 2023
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 7 Dec 2, 2022
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.5k Jan 8, 2023
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
Get your loadshedding schedule in your calendar and never be left in the dark! Open-source, up-to-date, and developer friendly.

Loadshedding schedules in your digital calendar. No apps, no ads, up-to-date, and developer friendly. Get it • Key Features • Using the data • Project

Boyd Kane 117 Apr 26, 2023
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 837 Dec 30, 2022
Fastest image quadtree stylization implementation to date, capable of hundreds of fps and avoiding ugly non-squares.

Quadim Fastest image quadtree stylization implementation to date, capable of hundreds of fps and avoiding ugly non-squares. 简体中文 如果你是从B站来的…… “Listen t

K--A______ 13 May 11, 2023