hutools/date/begin/
begin_of_week_with_sunday.rs

1use chrono::{Date, DateTime, Datelike, Duration, TimeZone};
2use std::ops::Sub;
3
4#[cfg(test)]
5mod test {
6    use super::*;
7    use chrono::Utc;
8
9    #[test]
10    fn begin_of_week_with_sunday_test() {
11        let date = Utc.ymd(2008, 8, 8);
12        let actual = Utc.ymd(2008, 8, 3);
13        let result = begin_of_week_with_sunday(date);
14        assert_eq!(result, actual);
15    }
16
17    #[test]
18    fn begin_of_week_with_sunday_test1() {
19        let date = Utc.ymd(2008, 8, 3);
20        let actual = Utc.ymd(2008, 8, 3);
21        let result = begin_of_week_with_sunday(date);
22        assert_eq!(result, actual);
23    }
24
25    #[test]
26    fn begin_of_week_with_sunday_with_time_test() {
27        let datetime = Utc.ymd(2008, 8, 8).and_hms(8, 8, 8);
28        let actual = Utc.ymd(2008, 8, 3);
29        let result = begin_of_week_with_sunday_with_time(datetime);
30        assert_eq!(result, actual);
31    }
32}
33
34/// Get the start of a week which start from sunday;
35/// 获取某个星期的开始日期(以周日为第一天)
36/// # Arguments
37///
38/// * `date`:
39///
40/// returns: Date<Tz>
41///
42/// # Examples
43///
44/// ```
45/// use chrono::{TimeZone, Utc};
46/// use hutools::date::begin_of_week_with_sunday;
47/// let date = Utc.ymd(2008,8,8);
48/// let actual = Utc.ymd(2008,8,3);
49/// let result = begin_of_week_with_sunday(date);
50/// assert_eq!(result, actual);
51/// ```
52pub fn begin_of_week_with_sunday<Tz: TimeZone>(date: Date<Tz>) -> Date<Tz> {
53    let num = date.weekday().number_from_sunday() - 1;
54    date.sub(Duration::days(num as i64))
55}
56
57/// Get the start of a week which start from sunday;
58/// 获取某个星期的开始日期(以周日为第一天)
59/// # Arguments
60///
61/// * `datetime`:
62///
63/// returns: Date<Tz>
64///
65/// # Examples
66///
67/// ```
68/// use chrono::{TimeZone, Utc};
69/// use hutools::date::begin_of_week_with_sunday_with_time;
70/// let datetime = Utc.ymd(2008,8,8).and_hms(8,8,8);
71/// let actual = Utc.ymd(2008,8,3);
72///let result = begin_of_week_with_sunday_with_time(datetime);
73/// assert_eq!(actual, result);
74/// ```
75pub fn begin_of_week_with_sunday_with_time<Tz: TimeZone>(datetime: DateTime<Tz>) -> Date<Tz> {
76    begin_of_week_with_sunday(datetime.date())
77}