chrono/src/offset/fixed.rs

227 lines
7.2 KiB
Rust
Raw Normal View History

// This is a part of Chrono.
// See README.md and LICENSE.txt for details.
//! The time zone which has a fixed offset from UTC.
use core::ops::{Add, Sub};
use core::fmt;
use oldtime::Duration as OldDuration;
`FixedOffset` is now the official "fixed offset value" type. This may sound strange, but the final type for the offset "value" was originally `time::Duration` (returned by `Offset::local_minus_utc`). This caused a lot of problems becaus adding `Duration` fully interacts with leap seconds and `Duration` itself is somewhat deprecated. This commit entirely replaces this role of `Duration` with `FixedOffset`. So if we had `Offset` and `Duration` to represent the "storage" offset type and the offset "value" in the past, we now have `Offset` and `FixedOffset`. Storage-to-value conversion is called to "fix" the offset---an apt term for the type. The list of actual changes: - The time zone offset is now restricted to UTC-23:59:59 through UTC+23:59:59, and no subsecond value is allowed. As described above, `FixedOffset` is now fully used for this purpose. - One can now add and subtract `FixedOffset` to/from timelike values. Replaces a temporary `chrono::offset::add_with_leapsecond` function. Datelike & non-timelike values are never affected by the offset. - UTC and local views to `Date<Tz>` are now identical. We keep relevant methods for the consistency right now. - `chrono::format::format` now receives `FixedOffset` in place of `(Old)Duration`. - `Offset` now has a `fix` method to resolve, or to "fix" the "storage" offset (`Offset`) to the offset "value" (`FixedOffset`). - `FixedOffset::{local_minus_utc, utc_minus_local}` methods are added. They no longer depend on `Duration` as well.
2017-02-06 18:43:59 +00:00
use Timelike;
use div::div_mod_floor;
Flattened intermediate implementation modules. There used to be multiple modules like `chrono::datetime` which only provide a single type `DateTime`. In retrospect, this module structure never reflected how people use those types; with the release of 0.3.0 `chrono::prelude` is a preferred way to glob-import types, and due to reexports `chrono::DateTime` and likes are also common enough. Therefore this commit removes those implementation modules and flattens the module structure. Specifically: Before After ---------------------------------- ---------------------------- chrono::date::Date chrono::Date chrono::date::MIN chrono::MIN_DATE chrono::date::MAX chrono::MAX_DATE chrono::datetime::DateTime chrono::DateTime chrono::datetime::TsSeconds chrono::TsSeconds chrono::datetime::serde::* chrono::serde::* chrono::naive::time::NaiveTime chrono::naive::NaiveTime chrono::naive::date::NaiveDate chrono::naive::NaiveDate chrono::naive::date::MIN chrono::naive::MIN_DATE chrono::naive::date::MAX chrono::naive::MAX_DATE chrono::naive::datetime::NaiveDateTime chrono::naive::NaiveDateTime chrono::naive::datetime::TsSeconds chrono::naive::TsSeconds chrono::naive::datetime::serde::* chrono::naive::serde::* chrono::offset::utc::UTC chrono::offset::UTC chrono::offset::fixed::FixedOffset chrono::offset::FixedOffset chrono::offset::local::Local chrono::offset::Local chrono::format::parsed::Parsed chrono::format::Parsed All internal documentation links have been updated (phew!) and verified with LinkChecker [1]. Probably we can automate this check in the future. [1] https://wummel.github.io/linkchecker/ Closes #161. Compared to the original proposal, `chrono::naive` is retained as we had `TsSeconds` types duplicated for `NaiveDateTime` and `DateTime` (legitimately).
2017-06-21 05:03:49 +00:00
use naive::{NaiveTime, NaiveDate, NaiveDateTime};
use DateTime;
use super::{TimeZone, Offset, LocalResult};
/// The time zone with fixed offset, from UTC-23:59:59 to UTC+23:59:59.
///
/// Using the [`TimeZone`](./trait.TimeZone.html) methods
/// on a `FixedOffset` struct is the preferred way to construct
/// `DateTime<FixedOffset>` instances. See the [`east`](#method.east) and
/// [`west`](#method.west) methods for examples.
2018-06-19 00:42:37 +00:00
#[derive(PartialEq, Eq, Hash, Copy, Clone)]
pub struct FixedOffset {
local_minus_utc: i32,
}
impl FixedOffset {
/// Makes a new `FixedOffset` for the Eastern Hemisphere with given timezone difference.
/// The negative `secs` means the Western Hemisphere.
///
/// Panics on the out-of-bound `secs`.
///
/// # Example
///
/// ~~~~
/// use chrono::{FixedOffset, TimeZone};
/// let hour = 3600;
/// let datetime = FixedOffset::east(5 * hour).ymd(2016, 11, 08)
/// .and_hms(0, 0, 0);
/// assert_eq!(&datetime.to_rfc3339(), "2016-11-08T00:00:00+05:00")
/// ~~~~
pub fn east(secs: i32) -> FixedOffset {
FixedOffset::east_opt(secs).expect("FixedOffset::east out of bounds")
}
/// Makes a new `FixedOffset` for the Eastern Hemisphere with given timezone difference.
/// The negative `secs` means the Western Hemisphere.
///
/// Returns `None` on the out-of-bound `secs`.
pub fn east_opt(secs: i32) -> Option<FixedOffset> {
if -86_400 < secs && secs < 86_400 {
Some(FixedOffset { local_minus_utc: secs })
} else {
None
}
}
/// Makes a new `FixedOffset` for the Western Hemisphere with given timezone difference.
/// The negative `secs` means the Eastern Hemisphere.
///
/// Panics on the out-of-bound `secs`.
///
/// # Example
///
/// ~~~~
/// use chrono::{FixedOffset, TimeZone};
/// let hour = 3600;
/// let datetime = FixedOffset::west(5 * hour).ymd(2016, 11, 08)
/// .and_hms(0, 0, 0);
/// assert_eq!(&datetime.to_rfc3339(), "2016-11-08T00:00:00-05:00")
/// ~~~~
pub fn west(secs: i32) -> FixedOffset {
FixedOffset::west_opt(secs).expect("FixedOffset::west out of bounds")
}
/// Makes a new `FixedOffset` for the Western Hemisphere with given timezone difference.
/// The negative `secs` means the Eastern Hemisphere.
///
/// Returns `None` on the out-of-bound `secs`.
pub fn west_opt(secs: i32) -> Option<FixedOffset> {
if -86_400 < secs && secs < 86_400 {
Some(FixedOffset { local_minus_utc: -secs })
} else {
None
}
}
`FixedOffset` is now the official "fixed offset value" type. This may sound strange, but the final type for the offset "value" was originally `time::Duration` (returned by `Offset::local_minus_utc`). This caused a lot of problems becaus adding `Duration` fully interacts with leap seconds and `Duration` itself is somewhat deprecated. This commit entirely replaces this role of `Duration` with `FixedOffset`. So if we had `Offset` and `Duration` to represent the "storage" offset type and the offset "value" in the past, we now have `Offset` and `FixedOffset`. Storage-to-value conversion is called to "fix" the offset---an apt term for the type. The list of actual changes: - The time zone offset is now restricted to UTC-23:59:59 through UTC+23:59:59, and no subsecond value is allowed. As described above, `FixedOffset` is now fully used for this purpose. - One can now add and subtract `FixedOffset` to/from timelike values. Replaces a temporary `chrono::offset::add_with_leapsecond` function. Datelike & non-timelike values are never affected by the offset. - UTC and local views to `Date<Tz>` are now identical. We keep relevant methods for the consistency right now. - `chrono::format::format` now receives `FixedOffset` in place of `(Old)Duration`. - `Offset` now has a `fix` method to resolve, or to "fix" the "storage" offset (`Offset`) to the offset "value" (`FixedOffset`). - `FixedOffset::{local_minus_utc, utc_minus_local}` methods are added. They no longer depend on `Duration` as well.
2017-02-06 18:43:59 +00:00
/// Returns the number of seconds to add to convert from UTC to the local time.
#[inline]
`FixedOffset` is now the official "fixed offset value" type. This may sound strange, but the final type for the offset "value" was originally `time::Duration` (returned by `Offset::local_minus_utc`). This caused a lot of problems becaus adding `Duration` fully interacts with leap seconds and `Duration` itself is somewhat deprecated. This commit entirely replaces this role of `Duration` with `FixedOffset`. So if we had `Offset` and `Duration` to represent the "storage" offset type and the offset "value" in the past, we now have `Offset` and `FixedOffset`. Storage-to-value conversion is called to "fix" the offset---an apt term for the type. The list of actual changes: - The time zone offset is now restricted to UTC-23:59:59 through UTC+23:59:59, and no subsecond value is allowed. As described above, `FixedOffset` is now fully used for this purpose. - One can now add and subtract `FixedOffset` to/from timelike values. Replaces a temporary `chrono::offset::add_with_leapsecond` function. Datelike & non-timelike values are never affected by the offset. - UTC and local views to `Date<Tz>` are now identical. We keep relevant methods for the consistency right now. - `chrono::format::format` now receives `FixedOffset` in place of `(Old)Duration`. - `Offset` now has a `fix` method to resolve, or to "fix" the "storage" offset (`Offset`) to the offset "value" (`FixedOffset`). - `FixedOffset::{local_minus_utc, utc_minus_local}` methods are added. They no longer depend on `Duration` as well.
2017-02-06 18:43:59 +00:00
pub fn local_minus_utc(&self) -> i32 {
self.local_minus_utc
}
/// Returns the number of seconds to add to convert from the local time to UTC.
#[inline]
`FixedOffset` is now the official "fixed offset value" type. This may sound strange, but the final type for the offset "value" was originally `time::Duration` (returned by `Offset::local_minus_utc`). This caused a lot of problems becaus adding `Duration` fully interacts with leap seconds and `Duration` itself is somewhat deprecated. This commit entirely replaces this role of `Duration` with `FixedOffset`. So if we had `Offset` and `Duration` to represent the "storage" offset type and the offset "value" in the past, we now have `Offset` and `FixedOffset`. Storage-to-value conversion is called to "fix" the offset---an apt term for the type. The list of actual changes: - The time zone offset is now restricted to UTC-23:59:59 through UTC+23:59:59, and no subsecond value is allowed. As described above, `FixedOffset` is now fully used for this purpose. - One can now add and subtract `FixedOffset` to/from timelike values. Replaces a temporary `chrono::offset::add_with_leapsecond` function. Datelike & non-timelike values are never affected by the offset. - UTC and local views to `Date<Tz>` are now identical. We keep relevant methods for the consistency right now. - `chrono::format::format` now receives `FixedOffset` in place of `(Old)Duration`. - `Offset` now has a `fix` method to resolve, or to "fix" the "storage" offset (`Offset`) to the offset "value" (`FixedOffset`). - `FixedOffset::{local_minus_utc, utc_minus_local}` methods are added. They no longer depend on `Duration` as well.
2017-02-06 18:43:59 +00:00
pub fn utc_minus_local(&self) -> i32 {
-self.local_minus_utc
}
}
impl TimeZone for FixedOffset {
type Offset = FixedOffset;
fn from_offset(offset: &FixedOffset) -> FixedOffset { *offset }
fn offset_from_local_date(&self, _local: &NaiveDate) -> LocalResult<FixedOffset> {
LocalResult::Single(*self)
}
fn offset_from_local_datetime(&self, _local: &NaiveDateTime) -> LocalResult<FixedOffset> {
LocalResult::Single(*self)
}
fn offset_from_utc_date(&self, _utc: &NaiveDate) -> FixedOffset { *self }
fn offset_from_utc_datetime(&self, _utc: &NaiveDateTime) -> FixedOffset { *self }
}
impl Offset for FixedOffset {
`FixedOffset` is now the official "fixed offset value" type. This may sound strange, but the final type for the offset "value" was originally `time::Duration` (returned by `Offset::local_minus_utc`). This caused a lot of problems becaus adding `Duration` fully interacts with leap seconds and `Duration` itself is somewhat deprecated. This commit entirely replaces this role of `Duration` with `FixedOffset`. So if we had `Offset` and `Duration` to represent the "storage" offset type and the offset "value" in the past, we now have `Offset` and `FixedOffset`. Storage-to-value conversion is called to "fix" the offset---an apt term for the type. The list of actual changes: - The time zone offset is now restricted to UTC-23:59:59 through UTC+23:59:59, and no subsecond value is allowed. As described above, `FixedOffset` is now fully used for this purpose. - One can now add and subtract `FixedOffset` to/from timelike values. Replaces a temporary `chrono::offset::add_with_leapsecond` function. Datelike & non-timelike values are never affected by the offset. - UTC and local views to `Date<Tz>` are now identical. We keep relevant methods for the consistency right now. - `chrono::format::format` now receives `FixedOffset` in place of `(Old)Duration`. - `Offset` now has a `fix` method to resolve, or to "fix" the "storage" offset (`Offset`) to the offset "value" (`FixedOffset`). - `FixedOffset::{local_minus_utc, utc_minus_local}` methods are added. They no longer depend on `Duration` as well.
2017-02-06 18:43:59 +00:00
fn fix(&self) -> FixedOffset { *self }
}
impl fmt::Debug for FixedOffset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let offset = self.local_minus_utc;
let (sign, offset) = if offset < 0 {('-', -offset)} else {('+', offset)};
let (mins, sec) = div_mod_floor(offset, 60);
let (hour, min) = div_mod_floor(mins, 60);
if sec == 0 {
write!(f, "{}{:02}:{:02}", sign, hour, min)
} else {
write!(f, "{}{:02}:{:02}:{:02}", sign, hour, min, sec)
}
}
}
impl fmt::Display for FixedOffset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self, f) }
}
2019-12-29 22:27:59 +00:00
// addition or subtraction of FixedOffset to/from Timelike values is the same as
`FixedOffset` is now the official "fixed offset value" type. This may sound strange, but the final type for the offset "value" was originally `time::Duration` (returned by `Offset::local_minus_utc`). This caused a lot of problems becaus adding `Duration` fully interacts with leap seconds and `Duration` itself is somewhat deprecated. This commit entirely replaces this role of `Duration` with `FixedOffset`. So if we had `Offset` and `Duration` to represent the "storage" offset type and the offset "value" in the past, we now have `Offset` and `FixedOffset`. Storage-to-value conversion is called to "fix" the offset---an apt term for the type. The list of actual changes: - The time zone offset is now restricted to UTC-23:59:59 through UTC+23:59:59, and no subsecond value is allowed. As described above, `FixedOffset` is now fully used for this purpose. - One can now add and subtract `FixedOffset` to/from timelike values. Replaces a temporary `chrono::offset::add_with_leapsecond` function. Datelike & non-timelike values are never affected by the offset. - UTC and local views to `Date<Tz>` are now identical. We keep relevant methods for the consistency right now. - `chrono::format::format` now receives `FixedOffset` in place of `(Old)Duration`. - `Offset` now has a `fix` method to resolve, or to "fix" the "storage" offset (`Offset`) to the offset "value" (`FixedOffset`). - `FixedOffset::{local_minus_utc, utc_minus_local}` methods are added. They no longer depend on `Duration` as well.
2017-02-06 18:43:59 +00:00
// adding or subtracting the offset's local_minus_utc value
// but keep keeps the leap second information.
// this should be implemented more efficiently, but for the time being, this is generic right now.
fn add_with_leapsecond<T>(lhs: &T, rhs: i32) -> T
where T: Timelike + Add<OldDuration, Output=T>
{
// extract and temporarily remove the fractional part and later recover it
let nanos = lhs.nanosecond();
let lhs = lhs.with_nanosecond(0).unwrap();
(lhs + OldDuration::seconds(i64::from(rhs))).with_nanosecond(nanos).unwrap()
`FixedOffset` is now the official "fixed offset value" type. This may sound strange, but the final type for the offset "value" was originally `time::Duration` (returned by `Offset::local_minus_utc`). This caused a lot of problems becaus adding `Duration` fully interacts with leap seconds and `Duration` itself is somewhat deprecated. This commit entirely replaces this role of `Duration` with `FixedOffset`. So if we had `Offset` and `Duration` to represent the "storage" offset type and the offset "value" in the past, we now have `Offset` and `FixedOffset`. Storage-to-value conversion is called to "fix" the offset---an apt term for the type. The list of actual changes: - The time zone offset is now restricted to UTC-23:59:59 through UTC+23:59:59, and no subsecond value is allowed. As described above, `FixedOffset` is now fully used for this purpose. - One can now add and subtract `FixedOffset` to/from timelike values. Replaces a temporary `chrono::offset::add_with_leapsecond` function. Datelike & non-timelike values are never affected by the offset. - UTC and local views to `Date<Tz>` are now identical. We keep relevant methods for the consistency right now. - `chrono::format::format` now receives `FixedOffset` in place of `(Old)Duration`. - `Offset` now has a `fix` method to resolve, or to "fix" the "storage" offset (`Offset`) to the offset "value" (`FixedOffset`). - `FixedOffset::{local_minus_utc, utc_minus_local}` methods are added. They no longer depend on `Duration` as well.
2017-02-06 18:43:59 +00:00
}
impl Add<FixedOffset> for NaiveTime {
type Output = NaiveTime;
#[inline]
fn add(self, rhs: FixedOffset) -> NaiveTime {
add_with_leapsecond(&self, rhs.local_minus_utc)
}
}
impl Sub<FixedOffset> for NaiveTime {
type Output = NaiveTime;
#[inline]
fn sub(self, rhs: FixedOffset) -> NaiveTime {
add_with_leapsecond(&self, -rhs.local_minus_utc)
}
}
impl Add<FixedOffset> for NaiveDateTime {
type Output = NaiveDateTime;
#[inline]
fn add(self, rhs: FixedOffset) -> NaiveDateTime {
add_with_leapsecond(&self, rhs.local_minus_utc)
}
}
impl Sub<FixedOffset> for NaiveDateTime {
type Output = NaiveDateTime;
#[inline]
fn sub(self, rhs: FixedOffset) -> NaiveDateTime {
add_with_leapsecond(&self, -rhs.local_minus_utc)
}
}
impl<Tz: TimeZone> Add<FixedOffset> for DateTime<Tz> {
type Output = DateTime<Tz>;
#[inline]
fn add(self, rhs: FixedOffset) -> DateTime<Tz> {
add_with_leapsecond(&self, rhs.local_minus_utc)
}
}
impl<Tz: TimeZone> Sub<FixedOffset> for DateTime<Tz> {
type Output = DateTime<Tz>;
#[inline]
fn sub(self, rhs: FixedOffset) -> DateTime<Tz> {
add_with_leapsecond(&self, -rhs.local_minus_utc)
}
}
#[cfg(test)]
mod tests {
use offset::TimeZone;
use super::FixedOffset;
#[test]
fn test_date_extreme_offset() {
// starting from 0.3 we don't have an offset exceeding one day.
// this makes everything easier!
assert_eq!(format!("{:?}", FixedOffset::east(86399).ymd(2012, 2, 29)),
"2012-02-29+23:59:59".to_string());
assert_eq!(format!("{:?}", FixedOffset::east(86399).ymd(2012, 2, 29).and_hms(5, 6, 7)),
"2012-02-29T05:06:07+23:59:59".to_string());
assert_eq!(format!("{:?}", FixedOffset::west(86399).ymd(2012, 3, 4)),
"2012-03-04-23:59:59".to_string());
assert_eq!(format!("{:?}", FixedOffset::west(86399).ymd(2012, 3, 4).and_hms(5, 6, 7)),
"2012-03-04T05:06:07-23:59:59".to_string());
}
}