With Day (ParsiDateTime) - parsicore/parsidate GitHub Wiki

Method with_day (on ParsiDateTime)

Creates a new ParsiDateTime instance with only the day component of the date changed, preserving the time.

Description

This method creates a new ParsiDateTime based on the current instance (self), replacing only the day component of the date part. The year, month, and all time components (hour, minute, second) are copied directly from the original self instance.

The crucial logic for changing the day and validating that the resulting date (original year, original month, new day) is valid according to Persian calendar rules (e.g., day within month bounds, considering leap years) is delegated to the underlying ParsiDate::with_day method.

Arguments

  • day: The desired new day of the month (u8 or similar integer type) for the new ParsiDateTime.

Returns

  • Ok(ParsiDateTime): If the underlying call to ParsiDate::with_day on the date component is successful (meaning the resulting date is valid), returns the new ParsiDateTime instance (with updated day and original time) wrapped in Ok.
  • Err(DateError::InvalidDate): Returns an error if the underlying call to ParsiDate::with_day fails. This occurs if:
    • The original date part of self was invalid.
    • The specified day is invalid for the original year and month (e.g., day 31 in Mehr, day 30 in Esfand of a common year, day 0).

Examples (Rust)

use parsidate::{ParsiDateTime, DateError, ParsiDate}; // Assuming these types exist

let dt = ParsiDateTime::new(1403, 7, 15, 12, 0, 0).unwrap(); // Mehr 15th, 1403 (Mehr has 30 days)

// --- Success Case: Change Day Within Valid Range ---
let dt_day_30_result = dt.with_day(30); // Change day to 30 (last day of Mehr)
assert!(dt_day_30_result.is_ok());
let dt_day_30 = dt_day_30_result.unwrap();

// Verify the new day and preserved time
assert_eq!(dt_day_30.day(), 30);
assert_eq!(dt_day_30.date(), ParsiDate::new(1403, 7, 30).unwrap());
assert_eq!(dt_day_30.time(), (12, 0, 0));


// --- Error Case: Attempting to Set an Invalid Day ---
// Try setting day to 31 in Mehr (Month 7), which only has 30 days.
let result_invalid_day = dt.with_day(31);
assert!(result_invalid_day.is_err());
assert!(matches!(result_invalid_day, Err(DateError::InvalidDate))); // Check error type

// Try setting day to 0
let result_day_zero = dt.with_day(0);
assert!(matches!(result_day_zero, Err(DateError::InvalidDate)));


// --- Example with Esfand ---
let dt_esfand_leap = ParsiDateTime::new(1403, 12, 1, 10, 0, 0).unwrap(); // 1403 is leap (30 days)
// Set to valid day 30
assert_eq!(dt_esfand_leap.with_day(30).unwrap().day(), 30);
// Attempt to set invalid day 31
assert!(matches!(dt_esfand_leap.with_day(31), Err(DateError::InvalidDate)));