Skip to content

Commit

Permalink
feat: Add function SetEndMonth and SetBeginMonth
Browse files Browse the repository at this point in the history
  • Loading branch information
sgaunet committed Dec 10, 2022
1 parent ed644fc commit 456cef2
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
22 changes: 22 additions & 0 deletions calcdatelib/calcdatelib.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,28 @@ func (d *Date) SetEndDate() *Date {
return d
}

func (d *Date) SetEndMonth() *Date {
d.second = 59
d.minute = 59
d.hour = 23
if d.month == 0 {
d.month = 12
}
d.day = DayInMonth(d.year, d.month)
return d
}

func (d *Date) SetBeginMonth() *Date {
d.second = 0
d.minute = 0
d.hour = 0
d.day = 1
if d.month == 0 {
d.month = 1
}
return d
}

func GetInterval(d1 *Date, d2 *Date) time.Duration {
diff := d1.Time().Sub(d2.Time())
if diff > 0 {
Expand Down
76 changes: 76 additions & 0 deletions calcdatelib/calcdatelib_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,3 +394,79 @@ func TestGetInterval(t *testing.T) {
})
}
}

func TestDate_SetEndMonth(t *testing.T) {
tests := []struct {
name string
date string
want time.Time
}{
{
name: "end of february",
date: "2022/02/05 01:02:03",
want: time.Date(2022, 2, 28, 23, 59, 59, 0, time.UTC),
},
{
name: "end of february",
date: "2022/02/05 ::",
want: time.Date(2022, 2, 28, 23, 59, 59, 0, time.UTC),
},
{
name: "end of december",
date: "2022/12/05 01:02:03",
want: time.Date(2022, 12, 31, 23, 59, 59, 0, time.UTC),
},
{
name: "end of january",
date: "2022/01/05 01:02:03",
want: time.Date(2022, 1, 31, 23, 59, 59, 0, time.UTC),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
d, _ := NewDate(tt.date, "%YYYY/%MM/%DD %hh:%mm:%ss", "UTC")
result := d.SetEndMonth().Time()
if result != tt.want {
t.Errorf("Date.SetEndMonth() = %v, want %v", result, tt.want)
}
})
}
}

func TestDate_SetBeginMonth(t *testing.T) {
tests := []struct {
name string
date string
want time.Time
}{
{
name: "begin of february",
date: "2022/02/05 01:02:03",
want: time.Date(2022, 2, 1, 0, 0, 0, 0, time.UTC),
},
{
name: "begin of december",
date: "2022/12/05 01:02:03",
want: time.Date(2022, 12, 1, 0, 0, 0, 0, time.UTC),
},
{
name: "begin of january",
date: "2022/01/05 01:02:03",
want: time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC),
},
{
name: "begin of january",
date: "2022/01/05 ::",
want: time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
d, _ := NewDate(tt.date, "%YYYY/%MM/%DD %hh:%mm:%ss", "UTC")
result := d.SetBeginMonth().Time()
if result != tt.want {
t.Errorf("Date.SetBeginMonth() = %v, want %v", result, tt.want)
}
})
}
}

0 comments on commit 456cef2

Please sign in to comment.