- Home ›
- Google AJAX Feed API入門 ›
- フィードの取得 ›
- HERE
日付の表示形式の変更
エントリに含まれる「publishedDate」プロパティの値にエントリの日付に関する情報が含まれています。今回はAPIとは直接関係がないのですが、取得した日付のデータを任意の形式に変更する方法について解説します。
1.日付の形式の変更方法
2.サンプル
「publishedDate」プロパティの値はそのまま表示して頂いてももちろん構いませんが、任意の書式で表示したい場合は一度 Dateクラスのオブジェクトを作成し、必要な日付要素を取得します。
「publishedDate」プロパティの値を使ってDateクラスのオブジェクトを作成するには次のように記述します。
var pdate = new Date(entry.publishedDate);
一度Dateクラスのオブジェクトを作成すれば、年、月、日、時、秒、分などの各日付要素を次のように取得することができます。
var pdate = new Date(entry.publishedDate); var pday = pdate.getDate(); var pmonth = pdate.getMonth() + 1; var pyear = pdate.getFullYear(); var phour = pdate.getHours(); var pminute = pdate.getMinutes(); var psecond = pdate.getSeconds();
※getMonthメソッドは0から11の値を返しますので注意して下さい。
この各日付要素を組み合わせることで任意の形式で日付を表示することが可能となります。
それでは簡単なサンプルで試してみます。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta http-equiv="Content-Script-Type" content="text/javascript"> <title>Google AJAX Feed API テスト</title> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript" src="./js/script5_1.js"></script> </head> <body> <p>Google AJAX Feed API テスト</p> <div id="feed"></div> </body> </html>
google.load("feeds", "1"); function initialize() { var feedurl = "http://googlejapan.blogspot.com/atom.xml"; var feed = new google.feeds.Feed(feedurl); feed.load(function (result){ if (!result.error){ var container = document.getElementById("feed"); var htmlstr = ""; htmlstr += '<h2><a href="' + result.feed.link + '">' + result.feed.title + '</a></h2>'; for (var i = 0; i < result.feed.entries.length; i++) { var entry = result.feed.entries[i]; htmlstr += '<h3><a href="' + entry.link + '">' + entry.title + '</a></h3>'; htmlstr += '<p>' + entry.contentSnippet + '</p>'; var pdate = new Date(entry.publishedDate); var strdate = (pdate.getMonth() + 1) + '月' + pdate.getDate() + '日'; htmlstr += '<p>日付 :' + strdate + '</p>'; } container.innerHTML = htmlstr; }else{ alert(result.error.code + ":" + result.error.message); } }); } google.setOnLoadCallback(initialize);
上記を実際にブラウザ見てみると次のように表示されます。
今回は日付に関する表示を「月日」だけにしました。このように日付の表示形式は任意の形式に変更することが可能です。
( Written by Tatsuo Ikura )