LoginSignup
1
1

More than 3 years have passed since last update.

moment.jsで「任意の日付から表示」を実装

Last updated at Posted at 2018-01-27

日付データを扱うのが苦手な私にとって大変便利なライブラリーを発見しました。
その名も「moment.js」です。

【Qiita】Moment.jsを使う
【公式サイト】
【公式サイト】使い方

下記にソースを書きます。
タイトルの本題のソースは"box_05"のところです。
あとは便利なのでその他の機能についても試してみました。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="/js/moment.js"></script>
    <title>moment.jsについて</title>
</head>
<body>
<style>
* {
    margin: 0;
    padding: 0;
}
a {
  color: #285294;
}

div[class^="box_"]{
    background: #FA8072;
    margin-bottom: 5px;
}


</style>
<div class="box_01"></div>
<div class="box_02"></div>
<div class="box_03"></div>
<div class="box_04"></div>
<div class="box_05"></div>
<div class="box_06"></div>
<div class="box_07">ブログ記事タイトル</div>
<div class="box_08"></div>
<hr>
<script>
// 『今の時間の』Dateオブジェクトが返される
$(function(){
var now = moment();
    $('.box_01').text('【box01】' + now.toDate());
});

// 『今日の年月日にフォーマットする』
$(function(){
    var now = moment();
    var formatnow = now.format('YYYY年MM月DD日');
    $('.box_02').text('【box02】' + formatnow);
});

// 『任意に選んだ日付の文字列からDateオブジェクト』
$(function(){
    var shougatsu = moment('2018-01-08');
    var formatshougatsu = shougatsu.format('YYYY年MM月DD日');
    $('.box_03').text('【box03】' + formatshougatsu);
});


// 『diffメソッドを使って時間の差分を算出』
$(function(){
    var fromDate = moment();
    var toDate   = moment('2018-01-30 01:08');
    var diff = toDate.diff(fromDate,);
    $('.box_04').text('【box04】' + diff);
});

// 『diffメソッドを使ってオープンのお知らせを告知する装置』
$(function(){
    var fromDate = moment();
    var toDate   = moment('2018-02-01 00:00');
    var diff = toDate.diff(fromDate,);

    if(diff <= 0){
    $('.box_05').html('【box05】<strong>2月より新装開店オープンいたしました</strong>');
    }
});

// 『現在時刻を表示する』
setInterval(function(){
    $('.box_06').html('【box06】' + moment().format('LTS'));
}, 1000);


// 『登校日より一週間まではnewをつける』
$(function(){
    var oneday = moment('2018-01-25');
    var kigen = moment([2018,0,26]).add(7, 'days');
    //console.log(oneday);
    //console.log(kigen);
    var diff = kigen.diff(oneday);
    //console.log(diff);
    if(diff >= 0){
        $('.box_07').prepend('【box07】<strong>期限付きnewマーク付与</strong>');
    }
});

</script>
</body>
</html>

追記(2018年11月25日) CDNで利用の場合

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/locale/ja.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>

localeを日本に選択する。(何故かlocaleが先)、その次にライブラリーを読み込む。
【公式】moment.js cdnjsページ

実例集
全89項目!Moment.js日付の操作&比較・実例

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