Skip to main content

TimeParts

Struct TimeParts 

Source
pub struct TimeParts {
Show 19 fields pub yr: Option<i64>, pub mo: Option<u8>, pub day: Option<u8>, pub hr: Option<u8>, pub min: Option<u8>, pub sec: Option<u8>, pub attos: Option<u64>, pub offset: Option<Offset>, pub iana_name: Option<LiteStr<49>>, pub is_leap_sec: bool, pub scale: Scale, pub wkday: Option<Weekday>, pub day_of_yr: Option<u16>, pub iso_wk_yr: Option<i64>, pub iso_wk: Option<u8>, pub wk_sun: Option<u8>, pub wk_mon: Option<u8>, pub meridiem: Option<Meridiem>, pub unix_timestamp_seconds: Option<i64>,
}
Expand description

A flexible, partially-filled representation of a civil datetime.

TimeParts is the central intermediate type used throughout the library for parsing, formatting, and converting between different time representations (CCSDS, ISO-like strings, chrono, jiff, Dt, etc.).

Most fields are optional, allowing partial dates/times. It also carries metadata such as the time scale, IANA zone name, leap-second flag, and various weekday/week-number representations.

  • Convert to [Dt] using TimeParts::to_dt.
  • Conversions to types from other crates require relevant features to be enabled.

Fields§

§yr: Option<i64>

Year (can be negative for BCE dates).

§mo: Option<u8>

Month of the year (1–12).

§day: Option<u8>

Day of the month (1–31).

§hr: Option<u8>

Hour of the day (0–23).

§min: Option<u8>

Minute of the hour (0–59).

§sec: Option<u8>

Second of the minute (0–60). Value 60 is used for leap seconds.

§attos: Option<u64>

Attoseconds (0 ≤ value < 10¹⁸).

§offset: Option<Offset>

Timezone offset from UTC.

§iana_name: Option<LiteStr<49>>

IANA timezone name (e.g. "America/New_York"), stored as ASCII.

§is_leap_sec: bool

Whether this instant represents a leap second.

§scale: Scale

The time scale this value belongs to (TAI, UTC, etc.).

§wkday: Option<Weekday>

Day of the week.

§day_of_yr: Option<u16>

Day of the year (1–366), corresponding to %j.

§iso_wk_yr: Option<i64>

ISO week year (%G / %g).

§iso_wk: Option<u8>

ISO week number (1–53), corresponding to %V.

§wk_sun: Option<u8>

Week number with Sunday as first day of week (0–53), %U.

§wk_mon: Option<u8>

Week number with Monday as first day of week (0–53), %W.

§meridiem: Option<Meridiem>

AM / PM indicator.

§unix_timestamp_seconds: Option<i64>

Unix timestamp in seconds (%s).

Implementations§

Source§

impl TimeParts

Source

pub const WIRE_VERSION: u8 = 1

Current wire format version.

Source

pub const WIRE_SIZE: usize = 120

Total size of the wire representation (120 bytes).

Source

pub fn to_wire_bytes(&self) -> [u8; 120]

Serializes TimeParts into a fixed 120-byte buffer.

Layout:

  • Byte 0: Version (WIRE_VERSION)
  • Bytes 1..120: Data (119 bytes)
Source

pub fn from_wire_bytes(bytes: &[u8]) -> Option<Self>

Deserializes TimeParts from exactly 120 bytes.

Returns None if the version byte is unknown or the data is invalid.

Source§

impl TimeParts

Source

pub fn days_since_1958_to_gregorian(days_since_epoch: i64) -> (i64, u8, u8)

Converts days since 1958-01-01 (midnight UTC/TAI) into Gregorian date. Pure integer arithmetic matching the CCSDS 301.0-B-4 Level 1 epoch.

Source

pub fn gregorian_to_days_since_1958(year: i64, month: u8, day: u8) -> i64

Exact inverse of days_since_1958_to_gregorian.

Source

pub fn from_ccsds_ccs(input: &[u8]) -> Result<TimeParts, DtErr>

Parses a CCSDS Calendar Segmented Time Code (CCS) into TimeParts.

Implements CCSDS 301.0-B-4 §3.4 (Level 1 only).

This function accepts a single-byte P-field followed by a BCD-encoded T-field. It supports both calendar variants:

  • Month/Day format (most common)
  • Day-of-Year format
§P-field
  • Must not have the extension bit set (only 1-byte P-fields are supported).
  • Code ID must be 101.
  • Subsecond resolution: 0 to 6 BCD octets (0–12 decimal digits).
§T-field
  • Year is encoded as 4 BCD digits (0001–9999).
  • Time of day uses BCD with leap second support (second == 60).
  • When a leap second is present, second is normalized to 59 and is_leap_second is set to true in the returned TimeParts.
§Epoch

1958-01-01 00:00:00 UTC (identical to CDS).

§Errors

Returns an error if the P-field is extended, the Code ID is wrong, BCD digits are invalid, field lengths are insufficient, or any component (month, day, DOY, hour, minute, second) is out of range.

The resulting TimeParts has scale = UTC.

Source

pub fn from_ccsds_c(input: &[u8]) -> Result<TimeParts, DtErr>

Parses a CCSDS Unsegmented Time Code (CUC) into TimeParts.

Implements CCSDS 301.0-B-4 §3.2 (Level 1), including full support for the extended 2-byte P-field defined in Issue 4.

§P-field
  • Supports both 1-byte and 2-byte P-fields.
  • Code ID must be 001 (1958-01-01 TAI epoch).
  • Coarse time: 1–7 octets total.
  • Fractional time: 0–10 octets total.
  • P-fields longer than 2 bytes are rejected.
§T-field
  • Coarse time is interpreted as seconds since the 1958 TAI epoch.
  • Fractional time is converted to attoseconds using exact integer scaling (value / 2^(8·n_frac)).
§Epoch

1958-01-01 00:00:00 TAI.

§Errors

Returns an error for empty input, insufficient length, invalid Code ID, unsupported further P-field extensions, or malformed T-field data.

The resulting TimeParts has scale = TAI.

Source

pub fn from_ccsds_d(input: &[u8]) -> Result<TimeParts, DtErr>

Parses a CCSDS Day Segmented Time Code (CDS) into TimeParts.

Implements CCSDS 301.0-B-4 §3.3 (Level 1).

§P-field
  • Supports optional 2-byte P-field.
  • Code ID must be 100.
  • Epoch bit must be 0 (1958-01-01 UTC epoch only).
  • Day count: 2 or 3 bytes.
  • Sub-millisecond resolution: none, 2 bytes (µs), or 4 bytes (2⁻³² of a ms).
§T-field
  • Day count is days since 1958-01-01 UTC.
  • Milliseconds since midnight are always 4 bytes.
  • Sub-millisecond field (if present) is converted to attoseconds.
§Leap Second Handling

This implementation correctly supports leap seconds. When millis_of_day represents 23:59:60 (i.e. ≥ 86,400,000 ms), second is set to 60 and is_leap_second is set to true in the returned TimeParts.

§Epoch

1958-01-01 00:00:00 UTC.

§Errors

Returns an error for empty input, wrong Code ID, non-Level-1 epoch, unsupported sub-millisecond code, insufficient length, or invalid data.

The resulting TimeParts has scale = UTC.

Source

pub fn from_ccsds_bin(input: &[u8]) -> Result<TimeParts, DtErr>

Auto-detects and parses a CCSDS binary time code (CUC, CDS, or CCS).

Examines the Code ID in the first P-field byte and dispatches to the appropriate parser:

This is a convenience wrapper. For stricter control or when the format is known in advance, prefer calling the specific from_ccsds_* function directly.

§Errors

Returns an error if the input is empty or the Code ID is not one of the three recognized Level 1 values.

Source§

impl TimeParts

Source

pub fn from_str( fmt: &str, input: &str, inp_can_end_before_fmt: bool, fmt_can_end_before_inp: bool, allow_partial_date: bool, ) -> Result<TimeParts, DtErr>

Low-level parser equivalent to strptime with a provided format string.

This is the core entry point for format-string based parsing in the library. It supports a large range of % directives (the same as jiff pretty much).

The parser populates a TimeParts struct with all fields that can be extracted from the input. After parsing, Self::finish is called automatically to apply defaults and validation.

§Parameters
  • fmt: The format string containing % directives.
  • input: The string to parse.
  • inp_can_end_before_fmt: If true, the input may end before the format string is fully consumed (extra format specifiers are ignored).
  • fmt_can_end_before_inp: If true, the format may end before the input is fully consumed (trailing characters in the input are allowed).
  • allow_partial_date: If true, a missing month/day will be defaulted to 1 instead of returning an [Incomplete] error.
§Errors

Returns DtErr for:

  • Parse failures (InvalidFormat, OutOfRange, etc.)
  • Incomplete data when allow_partial_date is false
  • Trailing characters (when fmt_can_end_before_inp is false)
Source

pub fn finish(&mut self, allow_partial_date: bool) -> Result<&mut Self, DtErr>

Finalizes a TimeParts after parsing by applying sensible defaults and performing validation.

This is called automatically by the various parsing paths (from_str, CCSDS parsers, etc.). It ensures the struct is in a consistent state before being turned into a full [Dt] or passed to other converters.

§Behavior
  • If a Unix timestamp is present, it takes precedence and the time components are defaulted to 00:00:00.000000000 with a UTC offset.
  • Otherwise:
    • Hour/minute/second/attoseconds/offset are defaulted to 0 / Utc.
    • Leap seconds (second == 60) are detected and flagged.
  • Date completeness is checked in this priority order:
    1. Calendar date (year, month, day)
    2. Ordinal date (year, day_of_year)
    3. ISO week date (iso_week_year, iso_week)
  • If allow_partial_date is true, missing month/day are defaulted to 1.
§Errors
Source§

impl TimeParts

Source

pub fn from_str_ccsds(input: &str) -> Result<Self, DtErr>

Generalized CCSDS ASCII Time Code parser (A or B variant).

  • Handles both calendar (%Y-%m-%d) and day-of-year (%Y-%j) formats.
    • e.g. 2000-01-01T12:00:00
  • All time components after the date portion are optional.
Source§

impl TimeParts

Source

pub fn to_ccsds_c( &self, n_coarse: u8, n_frac: u8, extension: bool, ) -> Result<([u8; 32], usize), DtErr>

Formats this TimeParts as a CCSDS C (CUC) binary time code.

  • Fully configurable for round-tripping with [from_ccsds_c].
  • Conforms to CCSDS 301.0-B-4 §3.2 (Level 1), including full support for the extended P-field (second octet) when n_coarse > 4 or n_frac > 3.
§Parameters
  • n_coarse: 1–7 (number of coarse-time octets)
  • n_frac: 0–10 (number of fractional octets)
  • extension: advisory flag (ignored when larger sizes force the second octet)
Source

pub fn to_ccsds_d( &self, n_day: u8, sub_ms_code: u8, extension: bool, ) -> Result<([u8; 32], usize), DtErr>

Formats this TimeParts as a CCSDS D (CDS) binary time code.

  • Fully configurable for round-tripping with [from_ccsds_d].
  • Conforms to CCSDS 301.0-B-4 §3.3 (Level 1): UTC day count + ms-of-day since 1958-01-01 UTC.
Source

pub fn to_ccsds_ccs( &self, use_doy: bool, n_subsec: u8, ) -> Result<([u8; 14], usize), DtErr>

Formats this TimeParts as a CCSDS CCS (Calendar Segmented Time Code).

Implements CCSDS 301.0-B-4 §3.4 (Level 1 only).

§Parameters
  • use_doy: false = Month/Day variant (most common), true = Day-of-Year variant
  • n_subsec: Number of subsecond BCD octets (06). Each octet holds 2 decimal digits.
§Returns

(buffer, written_len) — the P-field + T-field (big-endian BCD).

§Precision & Rounding

Fractional seconds are rounded to the nearest representable value at the chosen precision (exactly as to_ccsds_d does for milliseconds).

Source

pub fn to_ccsds_bin(&self) -> Result<([u8; 32], usize), DtErr>

Convenience method that automatically selects the most appropriate CCSDS binary time code based on this TimeParts’s [Scale].

§Automatic selection (matches common mission practice)
  • Scale::TAICUC (4 coarse + 4 fractional bytes)
  • Any other Scale (UTC, TT, GPS, TCG, …) → converted to UTC and uses CDS (2 day bytes + 4 ms bytes + 2-byte sub-ms)
Source§

impl TimeParts

Source

pub fn to_dt(&self) -> Result<Dt, DtErr>

Converts TimePartsDt.

  • Resulting Dt is on the TAI timescale.
  • If this TimeParts has a unix timestamp then it is used instead of anything else.
Source§

impl TimeParts

Source

pub fn to_str_ccsds(&self) -> Result<String, DtErr>

Returns this instant as a CCSDS ASCII Time Code (calendar variant A).

Example: "2025-04-17T14:30:45.123456789Z"

  • Uses T separator and trailing Z.
  • Fractional seconds are trimmed (no trailing zeros, no dot if zero).
  • Round-trips with Dt::from_str_ccsds / TimeParts::from_str_ccsds.
Source

pub fn to_str_ccsds_nf(&self, max_precision: usize) -> Result<String, DtErr>

Same as [to_str_ccsds] but lets you control the maximum number of fractional digits (0–18).

Source

pub fn to_ccsds_doy_str(&self) -> Result<String, DtErr>

Returns this instant as a CCSDS ASCII Time Code B (day-of-year variant).

Example: "2025-107T14:30:45.123456789Z"

Source

pub fn to_ccsds_doy_str_nf(&self, max_precision: usize) -> Result<String, DtErr>

Same as [to_ccsds_doy_str] but with configurable fractional precision.

Source§

impl TimeParts

Source

pub fn to_chrono_naive_datetime(&self) -> Result<NaiveDateTime, DtErr>

Converts TimePartschrono::NaiveDateTime (civil time, no TZ).

Source

pub fn to_chrono_datetime(&self) -> Result<DateTime<FixedOffset>, DtErr>

Converts TimePartschrono::DateTime.

  • If this TimeParts has a unix timestamp then it is used instead of anything else, timezones are ignored in this route.
  • If the "chrono-tz" feature is enabled then chronos tz features are used to parse the IANA name.
  • If the "chrono-tz" feature is not enabled then the library’s own tz handling will be used.
Source

pub fn to_chrono_timestamp(&self) -> Result<i64, DtErr>

Converts TimePartsi64.

  • If this TimeParts has a unix timestamp then it is used instead of anything else, timezones are ignored in this route.
  • If the "chrono-tz" feature is enabled then chronos tz features are used to parse the IANA name.
  • If the "chrono-tz" feature is not enabled then the library’s own tz handling will be used.
  • Uses TimeParts::to_chrono_datetime internally.
Source§

impl TimeParts

Source§

impl TimeParts

Source

pub fn new_utc() -> Self

Source

pub fn set_iana_name(&mut self, name: Option<&str>) -> &mut Self

Sets the IANA timezone name.

Trait Implementations§

Source§

impl Clone for TimeParts

Source§

fn clone(&self) -> TimeParts

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TimeParts

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for TimeParts

Source§

fn default() -> TimeParts

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for TimeParts

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for TimeParts

Source§

fn eq(&self, other: &TimeParts) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for TimeParts

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Tsify for TimeParts

Source§

const DECL: &'static str = "/**\n * A flexible, partially-filled representation of a civil datetime.\n *\n * `TimeParts` is the central intermediate type used throughout the library\n * for parsing, formatting, and converting between different time representations\n * (CCSDS, ISO-like strings, `chrono`, `jiff`, `Dt`, etc.).\n *\n * Most fields are optional, allowing partial dates/times. It also carries\n * metadata such as the time `scale`, IANA zone name, leap-second flag,\n * and various weekday/week-number representations.\n *\n * - Convert to [`Dt`] using [`TimeParts::to_dt`].\n * - Conversions to types from other crates require relevant features to\n * be enabled.\n */\nexport interface TimeParts {\n /**\n * Year (can be negative for BCE dates).\n */\n yr: number | null;\n /**\n * Month of the year (1\u{2013}12).\n */\n mo: number | null;\n /**\n * Day of the month (1\u{2013}31).\n */\n day: number | null;\n /**\n * Hour of the day (0\u{2013}23).\n */\n hr: number | null;\n /**\n * Minute of the hour (0\u{2013}59).\n */\n min: number | null;\n /**\n * Second of the minute (0\u{2013}60). Value 60 is used for leap seconds.\n */\n sec: number | null;\n /**\n * Attoseconds (0 \u{2264} value < 10\u{b9}\u{2078}).\n */\n attos: number | null;\n /**\n * Timezone offset from UTC.\n */\n offset: Offset | null;\n /**\n * IANA timezone name (e.g. `\\\"America/New_York\\\"`), stored as ASCII.\n */\n iana_name: LiteStr | null;\n /**\n * Whether this instant represents a leap second.\n */\n is_leap_sec: boolean;\n /**\n * The time scale this value belongs to (TAI, UTC, etc.).\n */\n scale: Scale;\n /**\n * Day of the week.\n */\n wkday: Weekday | null;\n /**\n * Day of the year (1\u{2013}366), corresponding to `%j`.\n */\n day_of_yr: number | null;\n /**\n * ISO week year (`%G` / `%g`).\n */\n iso_wk_yr: number | null;\n /**\n * ISO week number (1\u{2013}53), corresponding to `%V`.\n */\n iso_wk: number | null;\n /**\n * Week number with Sunday as first day of week (0\u{2013}53), `%U`.\n */\n wk_sun: number | null;\n /**\n * Week number with Monday as first day of week (0\u{2013}53), `%W`.\n */\n wk_mon: number | null;\n /**\n * AM / PM indicator.\n */\n meridiem: Meridiem | null;\n /**\n * Unix timestamp in seconds (`%s`).\n */\n unix_timestamp_seconds: number | null;\n}"

Source§

const SERIALIZATION_CONFIG: SerializationConfig

Source§

type JsType = JsType

Source§

fn into_js(&self) -> Result<Self::JsType, Error>
where Self: Serialize,

Source§

fn from_js<T>(js: T) -> Result<Self, Error>
where T: Into<JsValue>, Self: DeserializeOwned,

Source§

impl Copy for TimeParts

Source§

impl StructuralPartialEq for TimeParts

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,