DateTimeを使って先月と先月の最終日を求める
仕事で月初にキャンペーン処理をやるのだけど、その時に「前の月」と「前の月の最終日」が
必要になることが良くある。
JavaScriptだと、
var now = new Date(); new Date(now.getFullYear(), now.getMonth(), 0); // 日に0を与えると前の月の最終日
みたいなのが思いつくんだけど、Perlだとどうやればいいのかがよくわからない。
ということで、今やってるやり方は下のような感じ。
前月(YYYYMM)
my $now = DateTime->now; DateTime->new( year => $now->year, month => ($now->month - 1) || 12, # not 0 )->strftime('%Y%m');
前の月の最終日(YYYYMMDD)
my $now = DateTime->now; DateTime->last_day_of_month( year => $now->year, month => ($now->month - 1) || 12, # not 0 )->strftime('%Y%m%d');
もっと良いやり方あるのかしら。