pub(super) fn offset_from_utc_datetime(utc: &NaiveDateTime) -> MappedLocalTime<FixedOffset> { let offset = js_sys::Date::from(utc.and_utc()).get_timezone_offset();
MappedLocalTime::Single(FixedOffset::west_opt((offset as i32) * 60).unwrap())
}
pub(super) fn offset_from_local_datetime(
local: &NaiveDateTime,
) -> MappedLocalTime<FixedOffset> { letmut year = local.year(); if year < 100 { // The API in `js_sys` does not let us create a `Date` with negative years. // And values for years from `0` to `99` map to the years `1900` to `1999`. // Shift the value by a multiple of 400 years until it is `>= 100`. let shift_cycles = (year - 100).div_euclid(400);
year -= shift_cycles * 400;
} let js_date = js_sys::Date::new_with_year_month_day_hr_min_sec(
year as u32,
local.month0() as i32,
local.day() as i32,
local.hour() as i32,
local.minute() as i32,
local.second() as i32, // ignore milliseconds, our representation of leap seconds may be problematic
); let offset = js_date.get_timezone_offset(); // We always get a result, even if this time does not exist or is ambiguous.
MappedLocalTime::Single(FixedOffset::west_opt((offset as i32) * 60).unwrap())
}
}
#[cfg(unix)] mod tz_info;
/// The local timescale. /// /// Using the [`TimeZone`](./trait.TimeZone.html) methods /// on the Local struct is the preferred way to construct `DateTime<Local>` /// instances. /// /// # Example /// /// ``` /// use chrono::{DateTime, Local, TimeZone}; /// /// let dt1: DateTime<Local> = Local::now(); /// let dt2: DateTime<Local> = Local.timestamp_opt(0, 0).unwrap(); /// assert!(dt1 >= dt2); /// ``` #[derive(Copy, Clone, Debug)] #[cfg_attr(
any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"),
derive(Archive, Deserialize, Serialize),
archive(compare(PartialEq)),
archive_attr(derive(Clone, Copy, Debug))
)] #[cfg_attr(feature = "rkyv-validation", archive(check_bytes))] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pubstruct Local;
impl Local { /// Returns a `Date` which corresponds to the current date. #[deprecated(since = "0.4.23", note = "use `Local::now()` instead")] #[allow(deprecated)] #[must_use] pub fn today() -> Date<Local> {
Local::now().date()
}
/// Returns a `DateTime<Local>` which corresponds to the current date, time and offset from /// UTC. /// /// See also the similar [`Utc::now()`] which returns `DateTime<Utc>`, i.e. without the local /// offset. /// /// # Example /// /// ``` /// # #![allow(unused_variables)] /// # use chrono::{DateTime, FixedOffset, Local}; /// // Current local time /// let now = Local::now(); /// /// // Current local date /// let today = now.date_naive(); /// /// // Current local time, converted to `DateTime<FixedOffset>` /// let now_fixed_offset = Local::now().fixed_offset(); /// // or /// let now_fixed_offset: DateTime<FixedOffset> = Local::now().into(); /// /// // Current time in some timezone (let's use +05:00) /// // Note that it is usually more efficient to use `Utc::now` for this use case. /// let offset = FixedOffset::east_opt(5 * 60 * 60).unwrap(); /// let now_with_offset = Local::now().with_timezone(&offset); /// ``` pub fn now() -> DateTime<Local> {
Utc::now().with_timezone(&Local)
}
}
impl TimeZone for Local { type Offset = FixedOffset;
fn from_offset(_offset: &FixedOffset) -> Local {
Local
}
#[allow(deprecated)]
fn offset_from_local_date(&self, local: &NaiveDate) -> MappedLocalTime<FixedOffset> { // Get the offset at local midnight. self.offset_from_local_datetime(&local.and_time(NaiveTime::MIN))
}
#[cfg(windows)] impl Transition {
fn new(
transition_local: NaiveDateTime,
offset_before: FixedOffset,
offset_after: FixedOffset,
) -> Transition { // It is no problem if the transition time in UTC falls a couple of hours inside the buffer // space around the `NaiveDateTime` range (although it is very theoretical to have a // transition at midnight around `NaiveDate::(MIN|MAX)`. let transition_utc = transition_local.overflowing_sub_offset(offset_before);
Transition { transition_utc, offset_before, offset_after }
}
}
#[cfg(windows)] impl Ord for Transition {
fn cmp(&self, other: &Self) -> Ordering { self.transition_utc.cmp(&other.transition_utc)
}
}
// Calculate the time in UTC given a local time and transitions. // `transitions` must be sorted. #[cfg(windows)]
fn lookup_with_dst_transitions(
transitions: &[Transition],
dt: NaiveDateTime,
) -> MappedLocalTime<FixedOffset> {
for t in transitions.iter() { // A transition can result in the wall clock time going forward (creating a gap) or going // backward (creating a fold). We are interested in the earliest and latest wall time of the // transition, as this are the times between which `dt` does may not exist or is ambiguous. // // It is no problem if the transition times falls a couple of hours inside the buffer // space around the `NaiveDateTime` range (although it is very theoretical to have a // transition at midnight around `NaiveDate::(MIN|MAX)`. let (offset_min, offset_max) = match t.offset_after.local_minus_utc() > t.offset_before.local_minus_utc() { true => (t.offset_before, t.offset_after), false => (t.offset_after, t.offset_before),
}; let wall_earliest = t.transition_utc.overflowing_add_offset(offset_min); let wall_latest = t.transition_utc.overflowing_add_offset(offset_max);
#[test]
fn verify_correct_offsets() { let now = Local::now(); let from_local = Local.from_local_datetime(&now.naive_local()).unwrap(); let from_utc = Local.from_utc_datetime(&now.naive_utc());
iflet Some(dt) = today.and_hms_milli_opt(15, 2, 59, 1000) { let timestr = dt.time().to_string(); // the OS API may or may not support the leap second, // but there are only two sensible options.
assert!(
timestr == "15:02:60" || timestr == "15:03:00", "unexpected timestr {timestr:?}"
);
}
#[test] #[cfg(windows)]
fn test_lookup_with_dst_transitions() { let ymdhms = |y, m, d, h, n, s| {
NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_opt(h, n, s).unwrap()
};
#[test] #[cfg(windows)]
fn test_lookup_with_dst_transitions_limits() { // Transition beyond UTC year end doesn't panic in year of `NaiveDate::MAX` let std = FixedOffset::east_opt(3 * 60 * 60).unwrap(); let dst = FixedOffset::east_opt(4 * 60 * 60).unwrap(); let transitions = [
Transition::new(NaiveDateTime::MAX.with_month(7).unwrap(), std, dst),
Transition::new(NaiveDateTime::MAX, dst, std),
];
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MAX.with_month(3).unwrap()),
MappedLocalTime::Single(std)
);
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MAX.with_month(8).unwrap()),
MappedLocalTime::Single(dst)
); // Doesn't panic with `NaiveDateTime::MAX` as argument (which would be out of range when // converted to UTC).
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MAX),
MappedLocalTime::Ambiguous(dst, std)
);
// Transition before UTC year end doesn't panic in year of `NaiveDate::MIN` let std = FixedOffset::west_opt(3 * 60 * 60).unwrap(); let dst = FixedOffset::west_opt(4 * 60 * 60).unwrap(); let transitions = [
Transition::new(NaiveDateTime::MIN, std, dst),
Transition::new(NaiveDateTime::MIN.with_month(6).unwrap(), dst, std),
];
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MIN.with_month(3).unwrap()),
MappedLocalTime::Single(dst)
);
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MIN.with_month(8).unwrap()),
MappedLocalTime::Single(std)
); // Doesn't panic with `NaiveDateTime::MIN` as argument (which would be out of range when // converted to UTC).
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MIN),
MappedLocalTime::Ambiguous(std, dst)
);
}
#[test] #[cfg(feature = "rkyv-validation")]
fn test_rkyv_validation() { let local = Local; // Local is a ZST and serializes to 0 bytes let bytes = rkyv::to_bytes::<_, 0>(&local).unwrap();
assert_eq!(bytes.len(), 0);
// but is deserialized to an archived variant without a // wrapping object
assert_eq!(rkyv::from_bytes::<Local>(&bytes).unwrap(), super::ArchivedLocal);
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.