TOP ▲ itcore TOP PHP共通関数

uDateGetsumatsu 指定した日(年月)の月末日を返す。 20171203 201712 -> 21071231 | itcore 2017年

PHP JavaScript

PHP TOP

関数

<?php
// 指定した日(年月)の月末日を返す。 20171203 201712 -> 21071231
function uDateGetsumatsu($date_num) {
  $yyyymm = substr($date_num, 0, 6); // 201712
  return date('Ymt', strtotime("{$yyyymm}01")); // t:末日
}
?>

テスト

<?php include "uDateGetsumatsu.func"; ?>
<?php
$date_num = "20171103"; $ret = uDateGetsumatsu($date_num); echo "date_num=$date_num ret=$ret<br>\n";
$date_num = "20171203"; $ret = uDateGetsumatsu($date_num); echo "date_num=$date_num ret=$ret<br>\n";
$date_num = "201712"; $ret = uDateGetsumatsu($date_num); echo "date_num=$date_num ret=$ret<br>\n";
$date_num = "201902"; $ret = uDateGetsumatsu($date_num); echo "date_num=$date_num ret=$ret<br>\n";
$date_num = "202002"; $ret = uDateGetsumatsu($date_num); echo "date_num=$date_num ret=$ret<br>\n";
?>

実行結果

date_num=20171103 ret=20171130
date_num=20171203 ret=20171231
date_num=201712 ret=20171231
date_num=201902 ret=20190228
date_num=202002 ret=20200229

JavaScript TOP

関数

<?php include_once "uStr0.js"; ?>
<script>
// 指定した日(年月)の月末日を返す。 20171203 201712 -> 21071231
function uDateGetsumatsu(date_num) {
  date_num = String(date_num);
  var date = new Date(date_num.substr(0, 4), date_num.substr(4, 2), 0); // 日を0とすると月末
  return date.getFullYear() + uStr0((date.getMonth() + 1), 2) + uStr0(date.getDate(), 2); // getMonth()は月から1を引いた値になる。月と日は前0埋め。
}
</script>

テスト

<?php include "uDateGetsumatsu.js"; ?>
<script>
document.open();
var date_num = "20181103"; var ret = uDateGetsumatsu(date_num); document.writeln("date_num=" + date_num + " ret=" + ret + "<br>");
var date_num = "20181203"; var ret = uDateGetsumatsu(date_num); document.writeln("date_num=" + date_num + " ret=" + ret + "<br>");
var date_num = "201812"; var ret = uDateGetsumatsu(date_num); document.writeln("date_num=" + date_num + " ret=" + ret + "<br>");
var date_num = "201502"; var ret = uDateGetsumatsu(date_num); document.writeln("date_num=" + date_num + " ret=" + ret + "<br>");
var date_num = "201602"; var ret = uDateGetsumatsu(date_num); document.writeln("date_num=" + date_num + " ret=" + ret + "<br>");
document.close();
</script>

実行結果