Rails, moment : 「翌月の同じ日。ただし同じ日が存在しない場合は、それより前の一番近い存在する日」
JSのsetMonth, Go : 「翌月の同じ日。ただし同じ日が存在しない場合は、余った日数の分、翌月にずれ込む」
RustのchronoにはDuration::daysは存在するが、monthsやyearsは存在しない。Rustらしく「正しい」
Rails
irb(main):002> %w[2024-01-28 2024-01-29 2024-01-30 2024-01-31 2024-02-01].each { |d| puts "#{d} -> #{Date.parse(d) + 1.month}" }
2024-01-28 -> 2024-02-28
2024-01-29 -> 2024-02-29
2024-01-30 -> 2024-02-29
2024-01-31 -> 2024-02-29
2024-02-01 -> 2024-03-01
moment
> ["2024-01-28", "2024-01-29", "2024-01-30", "2024-01-31", "2024-02-01"].forEach(d => { console.log(d, "->", moment(d).add(1, "month").format("YYYY-MM-DD")); })
2024-01-28 -> 2024-02-28
2024-01-29 -> 2024-02-29
2024-01-30 -> 2024-02-29
2024-01-31 -> 2024-02-29
2024-02-01 -> 2024-03-01
JS: setMonth(getMonth() + 1)
["2024-01-28", "2024-01-29", "2024-01-30", "2024-01-31", "2024-02-01"].forEach(
d => {
date = new Date(d); date.setMonth(date.getMonth() + 1);
console.log(d, "->", (moment(date).format("YYYY-MM-DD")));
}
);
2024-01-28 -> 2024-02-28
2024-01-29 -> 2024-02-29
2024-01-30 -> 2024-03-01
2024-01-31 -> 2024-03-02
2024-02-01 -> 2024-03-01
Go
package main
import (
"fmt"
"time"
)
func main() {
dates := []string{"2024-01-28", "2024-01-29", "2024-01-30", "2024-01-31", "2024-02-01"}
for _, date := range dates {
added, err := time.Parse("2006-01-02", date)
if err != nil {
panic("time.Parse failed")
}
// 1ヶ月後の日付を計算
oneMonthLater := added.AddDate(0, 1, 0)
fmt.Printf("%s -> %s\n", date, oneMonthLater.Format("2006-01-02"))
}
}
2024-01-28 -> 2024-02-28
2024-01-29 -> 2024-02-29
2024-01-30 -> 2024-03-01
2024-01-31 -> 2024-03-02
2024-02-01 -> 2024-03-01