| 1 |
// This file is part of ICU4X. For terms of use, please see the file |
| 2 |
// called LICENSE at the top level of the ICU4X source tree |
| 3 |
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). |
| 4 |
|
| 5 |
#[cfg(feature = "unstable")] |
| 6 |
use crate::ZonedTime; |
| 7 |
#[cfg(feature = "unstable")] |
| 8 |
use crate::zone::ZoneNameTimestamp; |
| 9 |
use crate::{ |
| 10 |
DateTime, Time, TimeZoneInfo, ZonedDateTime, |
| 11 |
zone::{InvalidOffsetError, UtcOffset, iana::IanaParserBorrowed, models}, |
| 12 |
}; |
| 13 |
use core::str::FromStr; |
| 14 |
use icu_calendar::{AnyCalendarKind, AsCalendar, Date, DateError, Iso, RangeError}; |
| 15 |
use ixdtf::{ |
| 16 |
ParseError as Rfc9557ParseError, |
| 17 |
encoding::Utf8, |
| 18 |
parsers::IxdtfParser, |
| 19 |
records::{ |
| 20 |
IxdtfParseRecord, TimeZoneAnnotation, TimeZoneRecord, UtcOffsetRecord, UtcOffsetRecordOrZ, |
| 21 |
}, |
| 22 |
}; |
| 23 |
|
| 24 |
/// The error type for parsing RFC 9557 strings. |
| 25 |
#[derive(Debug, PartialEq, displaydoc::Display)] |
| 26 |
#[non_exhaustive] |
| 27 |
pub enum ParseError { |
| 28 |
/// Syntax error. |
| 29 |
#[displaydoc("Syntax error in the RFC 9557 string: {0}")] |
| 30 |
Syntax(Rfc9557ParseError), |
| 31 |
/// Parsed record is out of valid date range. |
| 32 |
#[displaydoc("Value out of range: {0}")] |
| 33 |
Range(RangeError), |
| 34 |
/// Parsed date and time records were not a valid ISO date. |
| 35 |
#[displaydoc("Parsed date and time records were not a valid ISO date: {0}")] |
| 36 |
Date(DateError), |
| 37 |
/// There were missing fields required to parse component. |
| 38 |
MissingFields, |
| 39 |
/// There were two offsets provided that were not consistent with each other. |
| 40 |
InconsistentTimeUtcOffsets, |
| 41 |
/// There was an invalid Offset. |
| 42 |
InvalidOffsetError, |
| 43 |
/// Parsed fractional digits had excessive precision beyond nanosecond. |
| 44 |
ExcessivePrecision, |
| 45 |
/// The set of time zone fields was not expected for the given type. |
| 46 |
/// For example, if a named time zone was present with offset-only parsing, |
| 47 |
/// or an offset was present with named-time-zone-only parsing. |
| 48 |
#[displaydoc("The set of time zone fields was not expected for the given type")] |
| 49 |
MismatchedTimeZoneFields, |
| 50 |
/// An unknown calendar was provided. |
| 51 |
UnknownCalendar, |
| 52 |
/// Expected a different calendar. |
| 53 |
#[displaydoc("Expected calendar {0} but found calendar {1}")] |
| 54 |
MismatchedCalendar(AnyCalendarKind, AnyCalendarKind), |
| 55 |
/// A timezone calculation is required to interpret this string, which is not supported. |
| 56 |
/// |
| 57 |
/// # Example |
| 58 |
/// ``` |
| 59 |
/// use icu::calendar::Iso; |
| 60 |
/// use icu::time::{ZonedDateTime, ParseError, zone::IanaParser}; |
| 61 |
/// |
| 62 |
/// // This timestamp is in UTC, and requires a time zone calculation in order to display a Zurich time. |
| 63 |
/// assert_eq!( |
| 64 |
/// ZonedDateTime::try_lenient_from_str("2024-08-12T12:32:00Z[Europe/Zurich]", Iso, IanaParser::new()).unwrap_err(), |
| 65 |
/// ParseError::RequiresCalculation, |
| 66 |
/// ); |
| 67 |
/// |
| 68 |
/// // These timestamps are in local time |
| 69 |
/// ZonedDateTime::try_lenient_from_str("2024-08-12T14:32:00+02:00[Europe/Zurich]", Iso, IanaParser::new()).unwrap(); |
| 70 |
/// ZonedDateTime::try_lenient_from_str("2024-08-12T14:32:00[Europe/Zurich]", Iso, IanaParser::new()).unwrap(); |
| 71 |
/// ``` |
| 72 |
#[displaydoc( |
| 73 |
"A timezone calculation is required to interpret this string, which is not supported" |
| 74 |
)] |
| 75 |
RequiresCalculation, |
| 76 |
} |
| 77 |
|
| 78 |
impl core::error::Error for ParseError {} |
| 79 |
|
| 80 |
impl From<Rfc9557ParseError> for ParseError { |
| 81 |
fn from(value: Rfc9557ParseError) -> Self { |
| 82 |
Self::Syntax(value) |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
impl From<RangeError> for ParseError { |
| 87 |
fn from(value: RangeError) -> Self { |
| 88 |
Self::Range(value) |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
impl From<DateError> for ParseError { |
| 93 |
fn from(value: DateError) -> Self { |
| 94 |
Self::Date(value) |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
impl From<InvalidOffsetError> for ParseError { |
| 99 |
fn from(_: InvalidOffsetError) -> Self { |
| 100 |
Self::InvalidOffsetError |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
impl From<icu_calendar::ParseError> for ParseError { |
| 105 |
fn from(value: icu_calendar::ParseError) -> Self { |
| 106 |
match value { |
| 107 |
icu_calendar::ParseError::MissingFields => Self::MissingFields, |
| 108 |
icu_calendar::ParseError::Range(r) => Self::Range(r), |
| 109 |
icu_calendar::ParseError::Syntax(s) => Self::Syntax(s), |
| 110 |
icu_calendar::ParseError::UnknownCalendar => Self::UnknownCalendar, |
| 111 |
icu_calendar::ParseError::MismatchedCalendar(a, b) => Self::MismatchedCalendar( |
| 112 |
a.try_into().unwrap_or(AnyCalendarKind::Iso), |
| 113 |
b.try_into().unwrap_or(AnyCalendarKind::Iso), |
| 114 |
), |
| 115 |
_ => unreachable!(), |
| 116 |
} |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
impl UtcOffset { |
| 121 |
fn try_from_utc_offset_record(record: UtcOffsetRecord) -> Result<Self, ParseError> { |
| 122 |
let hour_seconds = i32::from(record.hour()) * 3600; |
| 123 |
let minute_seconds = i32::from(record.minute()) * 60; |
| 124 |
Self::try_from_seconds( |
| 125 |
i32::from(record.sign() as i8) |
| 126 |
* (hour_seconds + minute_seconds + i32::from(record.second().unwrap_or(0))), |
| 127 |
) |
| 128 |
.map_err(Into::into) |
| 129 |
} |
| 130 |
} |
| 131 |
|
| 132 |
struct Intermediate<'a> { |
| 133 |
offset: Option<UtcOffsetRecord>, |
| 134 |
is_z: bool, |
| 135 |
iana_identifier: Option<&'a [u8]>, |
| 136 |
} |
| 137 |
|
| 138 |
impl<'a> Intermediate<'a> { |
| 139 |
fn try_from_ixdtf_record( |
| 140 |
ixdtf_record: &'a IxdtfParseRecord<'_, Utf8>, |
| 141 |
) -> Result<Self, ParseError> { |
| 142 |
let (offset, is_z, iana_identifier) = match ixdtf_record { |
| 143 |
// empty |
| 144 |
IxdtfParseRecord { |
| 145 |
offset: None, |
| 146 |
tz: None, |
| 147 |
.. |
| 148 |
} => (None, false, None), |
| 149 |
// -0800 |
| 150 |
IxdtfParseRecord { |
| 151 |
offset: Some(UtcOffsetRecordOrZ::Offset(offset)), |
| 152 |
tz: None, |
| 153 |
.. |
| 154 |
} => (Some(*offset), false, None), |
| 155 |
// Z |
| 156 |
IxdtfParseRecord { |
| 157 |
offset: Some(UtcOffsetRecordOrZ::Z), |
| 158 |
tz: None, |
| 159 |
.. |
| 160 |
} => (None, true, None), |
| 161 |
// [-0800] |
| 162 |
IxdtfParseRecord { |
| 163 |
offset: None, |
| 164 |
tz: |
| 165 |
Some(TimeZoneAnnotation { |
| 166 |
tz: TimeZoneRecord::Offset(offset), |
| 167 |
.. |
| 168 |
}), |
| 169 |
.. |
| 170 |
} => (Some(UtcOffsetRecord::MinutePrecision(*offset)), false, None), |
| 171 |
// -0800[-0800] |
| 172 |
IxdtfParseRecord { |
| 173 |
offset: Some(UtcOffsetRecordOrZ::Offset(offset)), |
| 174 |
tz: |
| 175 |
Some(TimeZoneAnnotation { |
| 176 |
tz: TimeZoneRecord::Offset(offset1), |
| 177 |
.. |
| 178 |
}), |
| 179 |
.. |
| 180 |
} => { |
| 181 |
let annotation_offset = UtcOffsetRecord::MinutePrecision(*offset1); |
| 182 |
if offset != &annotation_offset { |
| 183 |
return Err(ParseError::InconsistentTimeUtcOffsets); |
| 184 |
} |
| 185 |
(Some(*offset), false, None) |
| 186 |
} |
| 187 |
// -0800[America/Los_Angeles] |
| 188 |
IxdtfParseRecord { |
| 189 |
offset: Some(UtcOffsetRecordOrZ::Offset(offset)), |
| 190 |
tz: |
| 191 |
Some(TimeZoneAnnotation { |
| 192 |
tz: TimeZoneRecord::Name(iana_identifier), |
| 193 |
.. |
| 194 |
}), |
| 195 |
.. |
| 196 |
} => (Some(*offset), false, Some(*iana_identifier)), |
| 197 |
// Z[-0800] |
| 198 |
IxdtfParseRecord { |
| 199 |
offset: Some(UtcOffsetRecordOrZ::Z), |
| 200 |
tz: |
| 201 |
Some(TimeZoneAnnotation { |
| 202 |
tz: TimeZoneRecord::Offset(offset), |
| 203 |
.. |
| 204 |
}), |
| 205 |
.. |
| 206 |
} => (Some(UtcOffsetRecord::MinutePrecision(*offset)), true, None), |
| 207 |
// Z[America/Los_Angeles] |
| 208 |
IxdtfParseRecord { |
| 209 |
offset: Some(UtcOffsetRecordOrZ::Z), |
| 210 |
tz: |
| 211 |
Some(TimeZoneAnnotation { |
| 212 |
tz: TimeZoneRecord::Name(iana_identifier), |
| 213 |
.. |
| 214 |
}), |
| 215 |
.. |
| 216 |
} => (None, true, Some(*iana_identifier)), |
| 217 |
// [America/Los_Angeles] |
| 218 |
IxdtfParseRecord { |
| 219 |
offset: None, |
| 220 |
tz: |
| 221 |
Some(TimeZoneAnnotation { |
| 222 |
tz: TimeZoneRecord::Name(iana_identifier), |
| 223 |
.. |
| 224 |
}), |
| 225 |
.. |
| 226 |
} => (None, false, Some(*iana_identifier)), |
| 227 |
// non_exhaustive match: maybe something like [u-tz=uslax] in the future |
| 228 |
IxdtfParseRecord { |
| 229 |
tz: Some(TimeZoneAnnotation { tz, .. }), |
| 230 |
.. |
| 231 |
} => { |
| 232 |
debug_assert!(false, "unexpected TimeZoneRecord: {tz:?}"); |
| 233 |
(None, false, None) |
| 234 |
} |
| 235 |
}; |
| 236 |
Ok(Self { |
| 237 |
offset, |
| 238 |
is_z, |
| 239 |
iana_identifier, |
| 240 |
}) |
| 241 |
} |
| 242 |
|
| 243 |
fn offset_only(&self) -> Result<UtcOffset, ParseError> { |
| 244 |
let None = self.iana_identifier else { |
| 245 |
return Err(ParseError::MismatchedTimeZoneFields); |
| 246 |
}; |
| 247 |
if self.is_z { |
| 248 |
if let Some(offset) = self.offset |
| 249 |
&& offset != UtcOffsetRecord::zero() |
| 250 |
{ |
| 251 |
return Err(ParseError::RequiresCalculation); |
| 252 |
} |
| 253 |
return Ok(UtcOffset::zero()); |
| 254 |
} |
| 255 |
let Some(offset) = self.offset else { |
| 256 |
return Err(ParseError::MismatchedTimeZoneFields); |
| 257 |
}; |
| 258 |
UtcOffset::try_from_utc_offset_record(offset) |
| 259 |
} |
| 260 |
|
| 261 |
fn location_only( |
| 262 |
self, |
| 263 |
iana_parser: IanaParserBorrowed<'_>, |
| 264 |
) -> Result<TimeZoneInfo<models::Base>, ParseError> { |
| 265 |
let None = self.offset else { |
| 266 |
return Err(ParseError::MismatchedTimeZoneFields); |
| 267 |
}; |
| 268 |
let Some(iana_identifier) = self.iana_identifier else { |
| 269 |
if self.is_z { |
| 270 |
return Err(ParseError::RequiresCalculation); |
| 271 |
} |
| 272 |
return Err(ParseError::MismatchedTimeZoneFields); |
| 273 |
}; |
| 274 |
Ok(iana_parser |
| 275 |
.parse_from_utf8(iana_identifier) |
| 276 |
.with_offset(None)) |
| 277 |
} |
| 278 |
|
| 279 |
fn lenient( |
| 280 |
self, |
| 281 |
iana_parser: IanaParserBorrowed<'_>, |
| 282 |
) -> Result<TimeZoneInfo<models::Base>, ParseError> { |
| 283 |
let mut zone = match self.iana_identifier { |
| 284 |
Some(iana_identifier) => { |
| 285 |
if self.is_z { |
| 286 |
return Err(ParseError::RequiresCalculation); |
| 287 |
} |
| 288 |
iana_parser |
| 289 |
.parse_from_utf8(iana_identifier) |
| 290 |
.with_offset(None) |
| 291 |
} |
| 292 |
None if self.is_z => TimeZoneInfo::utc(), |
| 293 |
None => TimeZoneInfo::unknown(), |
| 294 |
}; |
| 295 |
|
| 296 |
if let Some(offset) = self.offset { |
| 297 |
let offset = UtcOffset::try_from_utc_offset_record(offset)?; |
| 298 |
if zone.offset().is_some_and(|i| i != offset) { |
| 299 |
return Err(ParseError::RequiresCalculation); |
| 300 |
} |
| 301 |
zone = zone.id().with_offset(Some(offset)); |
| 302 |
} |
| 303 |
Ok(zone) |
| 304 |
} |
| 305 |
|
| 306 |
fn all( |
| 307 |
self, |
| 308 |
iana_parser: IanaParserBorrowed<'_>, |
| 309 |
) -> Result<TimeZoneInfo<models::Base>, ParseError> { |
| 310 |
let Some(offset) = self.offset else { |
| 311 |
return Err(ParseError::MismatchedTimeZoneFields); |
| 312 |
}; |
| 313 |
let Some(iana_identifier) = self.iana_identifier else { |
| 314 |
return Err(ParseError::MismatchedTimeZoneFields); |
| 315 |
}; |
| 316 |
Ok(iana_parser |
| 317 |
.parse_from_utf8(iana_identifier) |
| 318 |
.with_offset(Some(UtcOffset::try_from_utc_offset_record(offset)?))) |
| 319 |
} |
| 320 |
} |
| 321 |
|
| 322 |
impl<A: AsCalendar> ZonedDateTime<A, UtcOffset> { |
| 323 |
/// Create a [`ZonedDateTime`] in any calendar from an RFC 9557 string. |
| 324 |
/// |
| 325 |
/// Returns an error if the string has a calendar annotation that does not |
| 326 |
/// match the calendar argument. |
| 327 |
/// |
| 328 |
/// This function is "strict": the string should have only an offset and no named time zone. |
| 329 |
pub fn try_offset_only_from_str(rfc_9557_str: &str, calendar: A) -> Result<Self, ParseError> { |
| 330 |
Self::try_offset_only_from_utf8(rfc_9557_str.as_bytes(), calendar) |
| 331 |
} |
| 332 |
|
| 333 |
/// Create a [`ZonedDateTime`] in any calendar from RFC 9557 syntax UTF-8 bytes. |
| 334 |
/// |
| 335 |
/// See [`Self:try_offset_only_from_str`](Self::try_offset_only_from_str). |
| 336 |
pub fn try_offset_only_from_utf8(rfc_9557_str: &[u8], calendar: A) -> Result<Self, ParseError> { |
| 337 |
let ixdtf_record = IxdtfParser::from_utf8(rfc_9557_str).parse()?; |
| 338 |
let date = Date::try_from_ixdtf_record(&ixdtf_record, calendar)?; |
| 339 |
let time = Time::try_from_ixdtf_record(&ixdtf_record)?; |
| 340 |
let zone = Intermediate::try_from_ixdtf_record(&ixdtf_record)?.offset_only()?; |
| 341 |
Ok(ZonedDateTime { date, time, zone }) |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
impl<A: AsCalendar> ZonedDateTime<A, TimeZoneInfo<models::AtTime>> { |
| 346 |
/// Create a [`ZonedDateTime`] in any calendar from an RFC 9557 string. |
| 347 |
/// |
| 348 |
/// Returns an error if the string has a calendar annotation that does not |
| 349 |
/// match the calendar argument. |
| 350 |
/// |
| 351 |
/// This function is "strict": the string should have only a named time zone and no offset. |
| 352 |
pub fn try_location_only_from_str( |
| 353 |
rfc_9557_str: &str, |
| 354 |
calendar: A, |
| 355 |
iana_parser: IanaParserBorrowed, |
| 356 |
) -> Result<Self, ParseError> { |
| 357 |
Self::try_location_only_from_utf8(rfc_9557_str.as_bytes(), calendar, iana_parser) |
| 358 |
} |
| 359 |
|
| 360 |
/// Create a [`ZonedDateTime`] in any calendar from RFC 9557 UTF-8 bytes. |
| 361 |
/// |
| 362 |
/// See [`Self::try_location_only_from_str`]. |
| 363 |
pub fn try_location_only_from_utf8( |
| 364 |
rfc_9557_str: &[u8], |
| 365 |
calendar: A, |
| 366 |
iana_parser: IanaParserBorrowed, |
| 367 |
) -> Result<Self, ParseError> { |
| 368 |
let ixdtf_record = IxdtfParser::from_utf8(rfc_9557_str).parse()?; |
| 369 |
let (date, rd) = Date::try_from_ixdtf_record_with_rd(&ixdtf_record, calendar)?; |
| 370 |
let time = Time::try_from_ixdtf_record(&ixdtf_record)?; |
| 371 |
let zone = Intermediate::try_from_ixdtf_record(&ixdtf_record)? |
| 372 |
.location_only(iana_parser)? |
| 373 |
.at_rd_time(rd, time); |
| 374 |
Ok(ZonedDateTime { date, time, zone }) |
| 375 |
} |
| 376 |
|
| 377 |
/// Create a [`ZonedDateTime`] in any calendar from an RFC 9557 string. |
| 378 |
/// |
| 379 |
/// Returns an error if the string has a calendar annotation that does not |
| 380 |
/// match the calendar argument. |
| 381 |
/// |
| 382 |
/// This function is "lenient": the string can have an offset, and named time zone, both, or |
| 383 |
/// neither. If the named time zone is missing, it is returned as Etc/Unknown. |
| 384 |
pub fn try_lenient_from_str( |
| 385 |
rfc_9557_str: &str, |
| 386 |
calendar: A, |
| 387 |
iana_parser: IanaParserBorrowed, |
| 388 |
) -> Result<Self, ParseError> { |
| 389 |
Self::try_lenient_from_utf8(rfc_9557_str.as_bytes(), calendar, iana_parser) |
| 390 |
} |
| 391 |
|
| 392 |
/// Create a [`ZonedDateTime`] in any calendar from RFC 9557 UTF-8 bytes. |
| 393 |
/// |
| 394 |
/// See [`Self::try_lenient_from_str`]. |
| 395 |
pub fn try_lenient_from_utf8( |
| 396 |
rfc_9557_str: &[u8], |
| 397 |
calendar: A, |
| 398 |
iana_parser: IanaParserBorrowed, |
| 399 |
) -> Result<Self, ParseError> { |
| 400 |
let ixdtf_record = IxdtfParser::from_utf8(rfc_9557_str).parse()?; |
| 401 |
let (date, rd) = Date::try_from_ixdtf_record_with_rd(&ixdtf_record, calendar)?; |
| 402 |
let time = Time::try_from_ixdtf_record(&ixdtf_record)?; |
| 403 |
let zone = Intermediate::try_from_ixdtf_record(&ixdtf_record)? |
| 404 |
.lenient(iana_parser)? |
| 405 |
.at_rd_time(rd, time); |
| 406 |
Ok(ZonedDateTime { date, time, zone }) |
| 407 |
} |
| 408 |
|
| 409 |
/// Create a [`ZonedDateTime`] in any calendar from an RFC 9557 string. |
| 410 |
/// |
| 411 |
/// Returns an error if the string has a calendar annotation that does not |
| 412 |
/// match the calendar argument. |
| 413 |
/// |
| 414 |
/// The string should have both an offset and a named time zone. |
| 415 |
/// |
| 416 |
/// For more information on RFC 9557, see the [`ixdtf`] crate. |
| 417 |
/// |
| 418 |
/// # Examples |
| 419 |
/// |
| 420 |
/// Basic usage: |
| 421 |
/// |
| 422 |
/// ``` |
| 423 |
/// use icu::calendar::cal::Hebrew; |
| 424 |
/// use icu::locale::subtags::subtag; |
| 425 |
/// use icu::time::{ |
| 426 |
/// TimeZone, TimeZoneInfo, ZonedDateTime, |
| 427 |
/// zone::{IanaParser, TimeZoneVariant, UtcOffset}, |
| 428 |
/// }; |
| 429 |
/// |
| 430 |
/// let zoneddatetime = ZonedDateTime::try_strict_from_str( |
| 431 |
/// "2024-08-08T12:08:19-05:00[America/Chicago][u-ca=hebrew]", |
| 432 |
/// Hebrew, |
| 433 |
/// IanaParser::new(), |
| 434 |
/// ) |
| 435 |
/// .unwrap(); |
| 436 |
/// |
| 437 |
/// assert_eq!(zoneddatetime.date.year().extended_year(), 5784); |
| 438 |
/// assert_eq!( |
| 439 |
/// zoneddatetime.date.month().to_input().code(), |
| 440 |
/// icu::calendar::types::MonthCode(tinystr::tinystr!(4, "M11")) |
| 441 |
/// ); |
| 442 |
/// assert_eq!(zoneddatetime.date.day_of_month().0, 4); |
| 443 |
/// |
| 444 |
/// assert_eq!(zoneddatetime.time.hour.number(), 12); |
| 445 |
/// assert_eq!(zoneddatetime.time.minute.number(), 8); |
| 446 |
/// assert_eq!(zoneddatetime.time.second.number(), 19); |
| 447 |
/// assert_eq!(zoneddatetime.time.subsecond.number(), 0); |
| 448 |
/// assert_eq!( |
| 449 |
/// zoneddatetime.zone.id(), |
| 450 |
/// TimeZone::from_iana_id("America/Chicago") |
| 451 |
/// ); |
| 452 |
/// assert_eq!( |
| 453 |
/// zoneddatetime.zone.offset(), |
| 454 |
/// Some(UtcOffset::try_from_seconds(-5 * 3600).unwrap()) |
| 455 |
/// ); |
| 456 |
/// let _ = zoneddatetime.zone.zone_name_timestamp(); |
| 457 |
/// ``` |
| 458 |
/// |
| 459 |
/// An RFC 9557 string can provide a time zone in two parts: the `DateTime` UTC Offset or the Time Zone |
| 460 |
/// Annotation. A `DateTime` UTC Offset is the time offset as laid out by RFC 3339; meanwhile, the Time |
| 461 |
/// Zone Annotation is the annotation laid out by RFC 9557 and is defined as a UTC offset or IANA Time |
| 462 |
/// Zone identifier. |
| 463 |
/// |
| 464 |
/// ## `DateTime` UTC Offsets |
| 465 |
/// |
| 466 |
/// Below is an example of a time zone from a `DateTime` UTC Offset. The syntax here is familiar to a RFC 3339 |
| 467 |
/// `DateTime` string. |
| 468 |
/// |
| 469 |
/// ``` |
| 470 |
/// use icu::calendar::Iso; |
| 471 |
/// use icu::time::{TimeZoneInfo, ZonedDateTime, zone::UtcOffset}; |
| 472 |
/// |
| 473 |
/// let tz_from_offset = ZonedDateTime::try_offset_only_from_str( |
| 474 |
/// "2024-08-08T12:08:19-05:00", |
| 475 |
/// Iso, |
| 476 |
/// ) |
| 477 |
/// .unwrap(); |
| 478 |
/// |
| 479 |
/// assert_eq!( |
| 480 |
/// tz_from_offset.zone, |
| 481 |
/// UtcOffset::try_from_seconds(-5 * 3600).unwrap() |
| 482 |
/// ); |
| 483 |
/// ``` |
| 484 |
/// |
| 485 |
/// ## Time Zone Annotations |
| 486 |
/// |
| 487 |
/// Below is an example of a time zone being provided by a time zone annotation. |
| 488 |
/// |
| 489 |
/// ``` |
| 490 |
/// use icu::calendar::Iso; |
| 491 |
/// use icu::locale::subtags::subtag; |
| 492 |
/// use icu::time::{ |
| 493 |
/// TimeZone, TimeZoneInfo, ZonedDateTime, |
| 494 |
/// zone::{IanaParser, TimeZoneVariant, UtcOffset}, |
| 495 |
/// }; |
| 496 |
/// |
| 497 |
/// let tz_from_offset_annotation = ZonedDateTime::try_offset_only_from_str( |
| 498 |
/// "2024-08-08T12:08:19[-05:00]", |
| 499 |
/// Iso, |
| 500 |
/// ) |
| 501 |
/// .unwrap(); |
| 502 |
/// let tz_from_iana_annotation = ZonedDateTime::try_location_only_from_str( |
| 503 |
/// "2024-08-08T12:08:19[America/Chicago]", |
| 504 |
/// Iso, |
| 505 |
/// IanaParser::new(), |
| 506 |
/// ) |
| 507 |
/// .unwrap(); |
| 508 |
/// |
| 509 |
/// assert_eq!( |
| 510 |
/// tz_from_offset_annotation.zone, |
| 511 |
/// UtcOffset::try_from_seconds(-5 * 3600).unwrap() |
| 512 |
/// ); |
| 513 |
/// |
| 514 |
/// assert_eq!( |
| 515 |
/// tz_from_iana_annotation.zone.id(), |
| 516 |
/// TimeZone(subtag!("uschi")) |
| 517 |
/// ); |
| 518 |
/// assert_eq!(tz_from_iana_annotation.zone.offset(), None); |
| 519 |
/// ``` |
| 520 |
/// |
| 521 |
/// ## UTC Offset and time zone annotations. |
| 522 |
/// |
| 523 |
/// An RFC 9557 string may contain both a UTC Offset and time zone annotation. This is fine as long as |
| 524 |
/// the time zone parts can be deemed as inconsistent or unknown consistency. |
| 525 |
/// |
| 526 |
/// ### `DateTime` UTC offset with UTC Offset annotation. |
| 527 |
/// |
| 528 |
/// These annotations must always be consistent as they should be either the same value or are inconsistent. |
| 529 |
/// |
| 530 |
/// ``` |
| 531 |
/// use icu::calendar::Iso; |
| 532 |
/// use icu::time::{ |
| 533 |
/// ParseError, TimeZone, TimeZoneInfo, ZonedDateTime, zone::UtcOffset, |
| 534 |
/// }; |
| 535 |
/// use tinystr::tinystr; |
| 536 |
/// |
| 537 |
/// let consistent_tz_from_both = ZonedDateTime::try_offset_only_from_str( |
| 538 |
/// "2024-08-08T12:08:19-05:00[-05:00]", |
| 539 |
/// Iso, |
| 540 |
/// ) |
| 541 |
/// .unwrap(); |
| 542 |
/// |
| 543 |
/// assert_eq!( |
| 544 |
/// consistent_tz_from_both.zone, |
| 545 |
/// UtcOffset::try_from_seconds(-5 * 3600).unwrap() |
| 546 |
/// ); |
| 547 |
/// |
| 548 |
/// let inconsistent_tz_from_both = ZonedDateTime::try_offset_only_from_str( |
| 549 |
/// "2024-08-08T12:08:19-05:00[+05:00]", |
| 550 |
/// Iso, |
| 551 |
/// ); |
| 552 |
/// |
| 553 |
/// assert!(matches!( |
| 554 |
/// inconsistent_tz_from_both, |
| 555 |
/// Err(ParseError::InconsistentTimeUtcOffsets) |
| 556 |
/// )); |
| 557 |
/// ``` |
| 558 |
pub fn try_strict_from_str( |
| 559 |
rfc_9557_str: &str, |
| 560 |
calendar: A, |
| 561 |
iana_parser: IanaParserBorrowed, |
| 562 |
) -> Result<Self, ParseError> { |
| 563 |
Self::try_strict_from_utf8(rfc_9557_str.as_bytes(), calendar, iana_parser) |
| 564 |
} |
| 565 |
|
| 566 |
/// Create a [`ZonedDateTime`] in any calendar from RFC 9557 UTF-8 bytes. |
| 567 |
/// |
| 568 |
/// See [`Self::try_strict_from_str`]. |
| 569 |
pub fn try_strict_from_utf8( |
| 570 |
rfc_9557_str: &[u8], |
| 571 |
calendar: A, |
| 572 |
iana_parser: IanaParserBorrowed, |
| 573 |
) -> Result<Self, ParseError> { |
| 574 |
let ixdtf_record = IxdtfParser::from_utf8(rfc_9557_str).parse()?; |
| 575 |
let (date, rd) = Date::try_from_ixdtf_record_with_rd(&ixdtf_record, calendar)?; |
| 576 |
let time = Time::try_from_ixdtf_record(&ixdtf_record)?; |
| 577 |
let zone = Intermediate::try_from_ixdtf_record(&ixdtf_record)? |
| 578 |
.all(iana_parser)? |
| 579 |
.at_rd_time(rd, time); |
| 580 |
Ok(ZonedDateTime { date, time, zone }) |
| 581 |
} |
| 582 |
} |
| 583 |
|
| 584 |
#[allow(deprecated)] |
| 585 |
impl<A: AsCalendar> ZonedDateTime<A, TimeZoneInfo<models::Full>> { |
| 586 |
/// Create a [`ZonedDateTime`] in any calendar from an RFC 9557 string. |
| 587 |
#[deprecated(since = "2.1.0", note = "use `try_strict_from_str`")] |
| 588 |
pub fn try_full_from_str( |
| 589 |
rfc_9557_str: &str, |
| 590 |
calendar: A, |
| 591 |
iana_parser: IanaParserBorrowed, |
| 592 |
offset_calculator: crate::zone::VariantOffsetsCalculatorBorrowed, |
| 593 |
) -> Result<Self, ParseError> { |
| 594 |
Self::try_full_from_utf8( |
| 595 |
rfc_9557_str.as_bytes(), |
| 596 |
calendar, |
| 597 |
iana_parser, |
| 598 |
offset_calculator, |
| 599 |
) |
| 600 |
} |
| 601 |
|
| 602 |
/// Create a [`ZonedDateTime`] in any calendar from RFC 9557 UTF-8 bytes. |
| 603 |
/// |
| 604 |
/// See [`Self::try_full_from_str`]. |
| 605 |
#[deprecated(since = "2.1.0", note = "use `try_strict_from_utf8`")] |
| 606 |
pub fn try_full_from_utf8( |
| 607 |
rfc_9557_str: &[u8], |
| 608 |
calendar: A, |
| 609 |
iana_parser: IanaParserBorrowed, |
| 610 |
offset_calculator: crate::zone::VariantOffsetsCalculatorBorrowed, |
| 611 |
) -> Result<Self, ParseError> { |
| 612 |
let ZonedDateTime { date, time, zone } = |
| 613 |
ZonedDateTime::try_strict_from_utf8(rfc_9557_str, calendar, iana_parser)?; |
| 614 |
Ok(ZonedDateTime { |
| 615 |
date, |
| 616 |
time, |
| 617 |
zone: zone.infer_variant(offset_calculator), |
| 618 |
}) |
| 619 |
} |
| 620 |
} |
| 621 |
|
| 622 |
#[cfg(feature = "unstable")] |
| 623 |
impl ZonedTime<UtcOffset> { |
| 624 |
/// Create a [`ZonedTime`] from an RFC 9557 string. |
| 625 |
/// |
| 626 |
/// This function is "strict": the string should have only an offset and no named time zone. |
| 627 |
pub fn try_offset_only_from_str(rfc_9557_str: &str) -> Result<Self, ParseError> { |
| 628 |
Self::try_offset_only_from_utf8(rfc_9557_str.as_bytes()) |
| 629 |
} |
| 630 |
|
| 631 |
/// Create a [`ZonedTime`] in any calendar from RFC 9557 syntax UTF-8 bytes. |
| 632 |
/// |
| 633 |
/// See [`Self:try_offset_only_from_str`](Self::try_offset_only_from_str). |
| 634 |
pub fn try_offset_only_from_utf8(rfc_9557_str: &[u8]) -> Result<Self, ParseError> { |
| 635 |
let ixdtf_record = IxdtfParser::from_utf8(rfc_9557_str).parse_time()?; |
| 636 |
let time = Time::try_from_ixdtf_record(&ixdtf_record)?; |
| 637 |
let zone = Intermediate::try_from_ixdtf_record(&ixdtf_record)?.offset_only()?; |
| 638 |
Ok(Self { time, zone }) |
| 639 |
} |
| 640 |
} |
| 641 |
|
| 642 |
#[cfg(feature = "unstable")] |
| 643 |
impl ZonedTime<TimeZoneInfo<models::AtTime>> { |
| 644 |
/// Create a [`ZonedTime`] from an RFC 9557 string. |
| 645 |
/// |
| 646 |
/// This function is "strict": the string should have only a named time zone and no offset. |
| 647 |
pub fn try_location_only_from_str( |
| 648 |
rfc_9557_str: &str, |
| 649 |
iana_parser: IanaParserBorrowed, |
| 650 |
) -> Result<Self, ParseError> { |
| 651 |
Self::try_location_only_from_utf8(rfc_9557_str.as_bytes(), iana_parser) |
| 652 |
} |
| 653 |
|
| 654 |
/// Create a [`ZonedTime`] from RFC 9557 UTF-8 bytes. |
| 655 |
/// |
| 656 |
/// See [`Self::try_location_only_from_str`]. |
| 657 |
pub fn try_location_only_from_utf8( |
| 658 |
rfc_9557_str: &[u8], |
| 659 |
iana_parser: IanaParserBorrowed, |
| 660 |
) -> Result<Self, ParseError> { |
| 661 |
use crate::zone::ZoneNameTimestamp; |
| 662 |
|
| 663 |
let ixdtf_record = IxdtfParser::from_utf8(rfc_9557_str).parse_time()?; |
| 664 |
let time = Time::try_from_ixdtf_record(&ixdtf_record)?; |
| 665 |
let zone = Intermediate::try_from_ixdtf_record(&ixdtf_record)? |
| 666 |
.location_only(iana_parser)? |
| 667 |
.with_zone_name_timestamp(ZoneNameTimestamp::far_in_future()); |
| 668 |
Ok(Self { time, zone }) |
| 669 |
} |
| 670 |
|
| 671 |
/// Create a [`ZonedTime`] from an RFC 9557 string. |
| 672 |
/// |
| 673 |
/// This function is "lenient": the string can have an offset, and named time zone, both, or |
| 674 |
/// neither. If the named time zone is missing, it is returned as Etc/Unknown. |
| 675 |
pub fn try_lenient_from_str( |
| 676 |
rfc_9557_str: &str, |
| 677 |
iana_parser: IanaParserBorrowed, |
| 678 |
) -> Result<Self, ParseError> { |
| 679 |
Self::try_lenient_from_utf8(rfc_9557_str.as_bytes(), iana_parser) |
| 680 |
} |
| 681 |
|
| 682 |
/// Create a [`ZonedTime`] from RFC 9557 UTF-8 bytes. |
| 683 |
/// |
| 684 |
/// See [`Self::try_lenient_from_str`]. |
| 685 |
pub fn try_lenient_from_utf8( |
| 686 |
rfc_9557_str: &[u8], |
| 687 |
iana_parser: IanaParserBorrowed, |
| 688 |
) -> Result<Self, ParseError> { |
| 689 |
let ixdtf_record = IxdtfParser::from_utf8(rfc_9557_str).parse_time()?; |
| 690 |
let time = Time::try_from_ixdtf_record(&ixdtf_record)?; |
| 691 |
let zone = Intermediate::try_from_ixdtf_record(&ixdtf_record)? |
| 692 |
.lenient(iana_parser)? |
| 693 |
.with_zone_name_timestamp(ZoneNameTimestamp::far_in_future()); |
| 694 |
Ok(Self { time, zone }) |
| 695 |
} |
| 696 |
|
| 697 |
/// Create a [`ZonedTime`] from an RFC 9557 string. |
| 698 |
/// |
| 699 |
/// The string should have both an offset and a named time zone. |
| 700 |
/// |
| 701 |
/// For more information on RFC 9557, see the [`ixdtf`] crate. |
| 702 |
/// |
| 703 |
/// # Examples |
| 704 |
/// |
| 705 |
/// Basic usage: |
| 706 |
/// |
| 707 |
/// ``` |
| 708 |
/// use icu::calendar::cal::Hebrew; |
| 709 |
/// use icu::locale::subtags::subtag; |
| 710 |
/// use icu::time::{ |
| 711 |
/// TimeZone, TimeZoneInfo, ZonedTime, |
| 712 |
/// zone::{IanaParser, TimeZoneVariant, UtcOffset}, |
| 713 |
/// }; |
| 714 |
/// |
| 715 |
/// let zonedtime = ZonedTime::try_strict_from_str( |
| 716 |
/// "T12:08:19-05:00[America/Chicago][u-ca=hebrew]", |
| 717 |
/// IanaParser::new(), |
| 718 |
/// ) |
| 719 |
/// .unwrap(); |
| 720 |
/// |
| 721 |
/// assert_eq!(zonedtime.time.hour.number(), 12); |
| 722 |
/// assert_eq!(zonedtime.time.minute.number(), 8); |
| 723 |
/// assert_eq!(zonedtime.time.second.number(), 19); |
| 724 |
/// assert_eq!(zonedtime.time.subsecond.number(), 0); |
| 725 |
/// assert_eq!(zonedtime.zone.id(), TimeZone(subtag!("uschi"))); |
| 726 |
/// assert_eq!( |
| 727 |
/// zonedtime.zone.offset(), |
| 728 |
/// Some(UtcOffset::try_from_seconds(-5 * 3600).unwrap()) |
| 729 |
/// ); |
| 730 |
/// let _ = zonedtime.zone.zone_name_timestamp(); |
| 731 |
/// ``` |
| 732 |
/// |
| 733 |
/// An RFC 9557 string can provide a time zone in two parts: the `DateTime` UTC Offset or the Time Zone |
| 734 |
/// Annotation. A `DateTime` UTC Offset is the time offset as laid out by RFC 3339; meanwhile, the Time |
| 735 |
/// Zone Annotation is the annotation laid out by RFC 9557 and is defined as a UTC offset or IANA Time |
| 736 |
/// Zone identifier. |
| 737 |
/// |
| 738 |
/// ## `DateTime` UTC Offsets |
| 739 |
/// |
| 740 |
/// Below is an example of a time zone from a `DateTime` UTC Offset. The syntax here is familiar to a RFC 3339 |
| 741 |
/// `DateTime` string. |
| 742 |
/// |
| 743 |
/// ``` |
| 744 |
/// use icu::calendar::Iso; |
| 745 |
/// use icu::time::{TimeZoneInfo, ZonedTime, zone::UtcOffset}; |
| 746 |
/// |
| 747 |
/// let tz_from_offset = |
| 748 |
/// ZonedTime::try_offset_only_from_str("T12:08:19-05:00").unwrap(); |
| 749 |
/// |
| 750 |
/// assert_eq!( |
| 751 |
/// tz_from_offset.zone, |
| 752 |
/// UtcOffset::try_from_seconds(-5 * 3600).unwrap() |
| 753 |
/// ); |
| 754 |
/// ``` |
| 755 |
/// |
| 756 |
/// ## Time Zone Annotations |
| 757 |
/// |
| 758 |
/// Below is an example of a time zone being provided by a time zone annotation. |
| 759 |
/// |
| 760 |
/// ``` |
| 761 |
/// use icu::calendar::Iso; |
| 762 |
/// use icu::locale::subtags::subtag; |
| 763 |
/// use icu::time::{ |
| 764 |
/// TimeZone, TimeZoneInfo, ZonedTime, |
| 765 |
/// zone::{IanaParser, TimeZoneVariant, UtcOffset}, |
| 766 |
/// }; |
| 767 |
/// |
| 768 |
/// let tz_from_offset_annotation = |
| 769 |
/// ZonedTime::try_offset_only_from_str("T12:08:19[-05:00]").unwrap(); |
| 770 |
/// let tz_from_iana_annotation = ZonedTime::try_location_only_from_str( |
| 771 |
/// "T12:08:19[America/Chicago]", |
| 772 |
/// IanaParser::new(), |
| 773 |
/// ) |
| 774 |
/// .unwrap(); |
| 775 |
/// |
| 776 |
/// assert_eq!( |
| 777 |
/// tz_from_offset_annotation.zone, |
| 778 |
/// UtcOffset::try_from_seconds(-5 * 3600).unwrap() |
| 779 |
/// ); |
| 780 |
/// |
| 781 |
/// assert_eq!( |
| 782 |
/// tz_from_iana_annotation.zone.id(), |
| 783 |
/// TimeZone(subtag!("uschi")) |
| 784 |
/// ); |
| 785 |
/// assert_eq!(tz_from_iana_annotation.zone.offset(), None); |
| 786 |
/// ``` |
| 787 |
/// |
| 788 |
/// ## UTC Offset and time zone annotations. |
| 789 |
/// |
| 790 |
/// An RFC 9557 string may contain both a UTC Offset and time zone annotation. This is fine as long as |
| 791 |
/// the time zone parts can be deemed as inconsistent or unknown consistency. |
| 792 |
/// |
| 793 |
/// ### `DateTime` UTC offset with UTC Offset annotation. |
| 794 |
/// |
| 795 |
/// These annotations must always be consistent as they should be either the same value or are inconsistent. |
| 796 |
/// |
| 797 |
/// ``` |
| 798 |
/// use icu::calendar::Iso; |
| 799 |
/// use icu::time::{ |
| 800 |
/// ParseError, TimeZone, TimeZoneInfo, ZonedTime, zone::UtcOffset, |
| 801 |
/// }; |
| 802 |
/// use tinystr::tinystr; |
| 803 |
/// |
| 804 |
/// let consistent_tz_from_both = |
| 805 |
/// ZonedTime::try_offset_only_from_str("T12:08:19-05:00[-05:00]").unwrap(); |
| 806 |
/// |
| 807 |
/// assert_eq!( |
| 808 |
/// consistent_tz_from_both.zone, |
| 809 |
/// UtcOffset::try_from_seconds(-5 * 3600).unwrap() |
| 810 |
/// ); |
| 811 |
/// |
| 812 |
/// let inconsistent_tz_from_both = |
| 813 |
/// ZonedTime::try_offset_only_from_str("T12:08:19-05:00[+05:00]"); |
| 814 |
/// |
| 815 |
/// assert!(matches!( |
| 816 |
/// inconsistent_tz_from_both, |
| 817 |
/// Err(ParseError::InconsistentTimeUtcOffsets) |
| 818 |
/// )); |
| 819 |
/// ``` |
| 820 |
pub fn try_strict_from_str( |
| 821 |
rfc_9557_str: &str, |
| 822 |
iana_parser: IanaParserBorrowed, |
| 823 |
) -> Result<Self, ParseError> { |
| 824 |
Self::try_strict_from_utf8(rfc_9557_str.as_bytes(), iana_parser) |
| 825 |
} |
| 826 |
|
| 827 |
/// Create a [`ZonedTime`] from RFC 9557 UTF-8 bytes. |
| 828 |
/// |
| 829 |
/// See [`Self::try_strict_from_str`]. |
| 830 |
pub fn try_strict_from_utf8( |
| 831 |
rfc_9557_str: &[u8], |
| 832 |
iana_parser: IanaParserBorrowed, |
| 833 |
) -> Result<Self, ParseError> { |
| 834 |
let ixdtf_record = IxdtfParser::from_utf8(rfc_9557_str).parse_time()?; |
| 835 |
let time = Time::try_from_ixdtf_record(&ixdtf_record)?; |
| 836 |
let zone = Intermediate::try_from_ixdtf_record(&ixdtf_record)? |
| 837 |
.all(iana_parser)? |
| 838 |
.with_zone_name_timestamp(ZoneNameTimestamp::far_in_future()); |
| 839 |
|
| 840 |
Ok(Self { time, zone }) |
| 841 |
} |
| 842 |
} |
| 843 |
|
| 844 |
impl FromStr for DateTime<Iso> { |
| 845 |
type Err = ParseError; |
| 846 |
fn from_str(rfc_9557_str: &str) -> Result<Self, Self::Err> { |
| 847 |
Self::try_from_str(rfc_9557_str, Iso) |
| 848 |
} |
| 849 |
} |
| 850 |
|
| 851 |
impl<A: AsCalendar> DateTime<A> { |
| 852 |
/// Creates a [`DateTime`] in any calendar from an RFC 9557 string. |
| 853 |
/// |
| 854 |
/// Returns an error if the string has a calendar annotation that does not |
| 855 |
/// match the calendar argument. |
| 856 |
/// |
| 857 |
/// ✨ *Enabled with the `ixdtf` Cargo feature.* |
| 858 |
/// |
| 859 |
/// # Examples |
| 860 |
/// |
| 861 |
/// ``` |
| 862 |
/// use icu::calendar::cal::Hebrew; |
| 863 |
/// use icu::time::DateTime; |
| 864 |
/// |
| 865 |
/// let datetime = |
| 866 |
/// DateTime::try_from_str("2024-07-17T16:01:17.045[u-ca=hebrew]", Hebrew) |
| 867 |
/// .unwrap(); |
| 868 |
/// |
| 869 |
/// assert_eq!(datetime.date.era_year().year, 5784); |
| 870 |
/// assert_eq!( |
| 871 |
/// datetime.date.month().to_input().code(), |
| 872 |
/// icu::calendar::types::MonthCode(tinystr::tinystr!(4, "M10")) |
| 873 |
/// ); |
| 874 |
/// assert_eq!(datetime.date.day_of_month().0, 11); |
| 875 |
/// |
| 876 |
/// assert_eq!(datetime.time.hour.number(), 16); |
| 877 |
/// assert_eq!(datetime.time.minute.number(), 1); |
| 878 |
/// assert_eq!(datetime.time.second.number(), 17); |
| 879 |
/// assert_eq!(datetime.time.subsecond.number(), 45000000); |
| 880 |
/// ``` |
| 881 |
pub fn try_from_str(rfc_9557_str: &str, calendar: A) -> Result<Self, ParseError> { |
| 882 |
Self::try_from_utf8(rfc_9557_str.as_bytes(), calendar) |
| 883 |
} |
| 884 |
|
| 885 |
/// Creates a [`DateTime`] in any calendar from an RFC 9557 string. |
| 886 |
/// |
| 887 |
/// See [`Self::try_from_str()`]. |
| 888 |
/// |
| 889 |
/// ✨ *Enabled with the `ixdtf` Cargo feature.* |
| 890 |
pub fn try_from_utf8(rfc_9557_str: &[u8], calendar: A) -> Result<Self, ParseError> { |
| 891 |
let ixdtf_record = IxdtfParser::from_utf8(rfc_9557_str).parse()?; |
| 892 |
let date = Date::try_from_ixdtf_record(&ixdtf_record, calendar)?; |
| 893 |
let time = Time::try_from_ixdtf_record(&ixdtf_record)?; |
| 894 |
Ok(Self { date, time }) |
| 895 |
} |
| 896 |
} |
| 897 |
|
| 898 |
impl Time { |
| 899 |
/// Creates a [`Time`] from an RFC 9557 string of a time. |
| 900 |
/// |
| 901 |
/// Does not support parsing an RFC 9557 string with a date and time; for that, use [`DateTime`]. |
| 902 |
/// |
| 903 |
/// ✨ *Enabled with the `ixdtf` Cargo feature.* |
| 904 |
/// |
| 905 |
/// # Examples |
| 906 |
/// |
| 907 |
/// ``` |
| 908 |
/// use icu::time::Time; |
| 909 |
/// |
| 910 |
/// let time = Time::try_from_str("16:01:17.045").unwrap(); |
| 911 |
/// |
| 912 |
/// assert_eq!(time.hour.number(), 16); |
| 913 |
/// assert_eq!(time.minute.number(), 1); |
| 914 |
/// assert_eq!(time.second.number(), 17); |
| 915 |
/// assert_eq!(time.subsecond.number(), 45000000); |
| 916 |
/// ``` |
| 917 |
pub fn try_from_str(rfc_9557_str: &str) -> Result<Self, ParseError> { |
| 918 |
Self::try_from_utf8(rfc_9557_str.as_bytes()) |
| 919 |
} |
| 920 |
|
| 921 |
/// Creates a [`Time`] in the ISO-8601 calendar from an RFC 9557 string. |
| 922 |
/// |
| 923 |
/// ✨ *Enabled with the `ixdtf` Cargo feature.* |
| 924 |
/// |
| 925 |
/// See [`Self::try_from_str()`]. |
| 926 |
pub fn try_from_utf8(rfc_9557_str: &[u8]) -> Result<Self, ParseError> { |
| 927 |
let ixdtf_record = IxdtfParser::from_utf8(rfc_9557_str).parse_time()?; |
| 928 |
Self::try_from_ixdtf_record(&ixdtf_record) |
| 929 |
} |
| 930 |
|
| 931 |
fn try_from_ixdtf_record( |
| 932 |
ixdtf_record: &IxdtfParseRecord<'_, Utf8>, |
| 933 |
) -> Result<Self, ParseError> { |
| 934 |
let time_record = ixdtf_record.time.ok_or(ParseError::MissingFields)?; |
| 935 |
|
| 936 |
let nanosecond = time_record |
| 937 |
.fraction |
| 938 |
.map(|fraction| { |
| 939 |
fraction |
| 940 |
.to_nanoseconds() |
| 941 |
.ok_or(ParseError::ExcessivePrecision) |
| 942 |
}) |
| 943 |
.transpose()? |
| 944 |
.unwrap_or_default(); |
| 945 |
|
| 946 |
// values are in range by construction |
| 947 |
Ok(Time { |
| 948 |
hour: crate::types::Hour(time_record.hour), |
| 949 |
minute: crate::types::Minute(time_record.minute), |
| 950 |
second: crate::types::Second(time_record.second), |
| 951 |
subsecond: crate::types::Nanosecond(nanosecond), |
| 952 |
}) |
| 953 |
} |
| 954 |
} |
| 955 |
|
| 956 |
impl FromStr for Time { |
| 957 |
type Err = ParseError; |
| 958 |
fn from_str(rfc_9557_str: &str) -> Result<Self, Self::Err> { |
| 959 |
Self::try_from_str(rfc_9557_str) |
| 960 |
} |
| 961 |
} |
| 962 |
|
| 963 |
#[cfg(test)] |
| 964 |
mod test { |
| 965 |
use super::*; |
| 966 |
use crate::TimeZone; |
| 967 |
|
| 968 |
#[test] |
| 969 |
fn max_possible_rfc_9557_utc_offset() { |
| 970 |
assert_eq!( |
| 971 |
ZonedDateTime::try_offset_only_from_str("2024-08-08T12:08:19+23:59:59.999999999", Iso) |
| 972 |
.unwrap_err(), |
| 973 |
ParseError::InvalidOffsetError |
| 974 |
); |
| 975 |
} |
| 976 |
|
| 977 |
#[test] |
| 978 |
fn zone_calculations() { |
| 979 |
ZonedDateTime::try_offset_only_from_str("2024-08-08T12:08:19Z", Iso).unwrap(); |
| 980 |
assert_eq!( |
| 981 |
ZonedDateTime::try_offset_only_from_str("2024-08-08T12:08:19Z[+08:00]", Iso) |
| 982 |
.unwrap_err(), |
| 983 |
ParseError::RequiresCalculation |
| 984 |
); |
| 985 |
assert_eq!( |
| 986 |
ZonedDateTime::try_offset_only_from_str("2024-08-08T12:08:19Z[Europe/Zurich]", Iso) |
| 987 |
.unwrap_err(), |
| 988 |
ParseError::MismatchedTimeZoneFields |
| 989 |
); |
| 990 |
} |
| 991 |
|
| 992 |
#[test] |
| 993 |
fn future_zone() { |
| 994 |
let result = ZonedDateTime::try_location_only_from_str( |
| 995 |
"2024-08-08T12:08:19[Future/Zone]", |
| 996 |
Iso, |
| 997 |
IanaParserBorrowed::new(), |
| 998 |
) |
| 999 |
.unwrap(); |
| 1000 |
assert_eq!(result.zone.id(), TimeZone::UNKNOWN); |
| 1001 |
assert_eq!(result.zone.offset(), None); |
| 1002 |
} |
| 1003 |
|
| 1004 |
#[test] |
| 1005 |
fn lax() { |
| 1006 |
ZonedDateTime::try_location_only_from_str( |
| 1007 |
"2024-10-18T15:44[America/Los_Angeles]", |
| 1008 |
icu_calendar::cal::Gregorian, |
| 1009 |
IanaParserBorrowed::new(), |
| 1010 |
) |
| 1011 |
.unwrap(); |
| 1012 |
} |
| 1013 |
} |