0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「1ヶ月後」の定義

Last updated at Posted at 2024-12-13

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?