日付の表示形式の変更
エントリに含まれる「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"> <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="http://www.google.com/jsapi?key=(key)"> </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://www.hyuki.com/d/rss.xml";
var feed = new google.feeds.Feed(feedurl);
feed.setNumEntries(8);
feed.load(dispfeed);
function dispfeed(result){
if (!result.error){
var container = document.getElementById("feed");
var htmlstr = "";
htmlstr += '<h2><a href="' + result.feed.link + '">' + result.feed.title + '</a></h2>';
htmlstr += "<p>" + result.feed.description + "</p>";
htmlstr += "<ul>";
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
htmlstr += "<li>"
htmlstr += '<a href="' + entry.link + '">' + entry.title + '</a>';
var strdate = createDateString(entry.publishedDate);
htmlstr += "(" + strdate + ")";
htmlstr += "</li>"
}
htmlstr += "</ul>";
container.innerHTML = htmlstr;
}else{
alert(result.error.code + ":" + result.error.message);
}
}
}
function createDateString(publishedDate){
var pdate = new Date(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();
var strdate = pyear + "年" + pmonth + "月" + pday + "日" +
phour + "時" + pminute + "分" + psecond + "秒";
return strdate;
}
google.setOnLoadCallback(initialize);
上記を実際にブラウザ見てみると次のように表示されます。