2015年2月2日月曜日

HTML5(日付の表示方法)

HTML5アプリ開発で、日付の表示方法について説明します。

今日の日付は、JavaScriptでnew Date()で取得します。
toLocaleDateString、toISOString関数を使って文字列表現します。

実際にサンプルを使って、試してみます。
最初に"MM.DD.YY"の固定形式で日付表示して、次の行に日付変換してISO形式で表示します。

1) id="today"要素dateElのテキスト部分に今日(today)をtoLocaleDateStringをつかって、[2015年2月2日]の形式で日付を設定します。

2) toISOStringを使って、ISO日付形式(YYYY-MM-DDTHH:mm:ss.sssZ)で文字列変換しますします
3) setAttributeを使ってdatetime属性に日付を設定して、
4) HTML側でtimeタグ内でdatetime属性を使用して、日付表示します

【サンプル】
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta charset="UTF-8" />
 <title>Using the HTML5 Time Element</title>
 <script>
function assignDate() {
  var dateEl = document.getElementById("today");
  var today = new Date();
  dateEl.textContent = today.toLocaleDateString();
  dateEl.setAttribute("datetime", today.toISOString());
}
window.addEventListener("load", assignDate);
 </script>
</head>
<body>
 <h1>HTML5 Time Element</h1>
 <p>HTML 2.0 was published on
    <time datetime="2015-02-05">02.02.2015</time>.</p>
 <p>Today is <time id="today" datetime=""></time>.</p>

</body>
</html>


【結果】
尚、ブラウザごとに表示結果が異なるので、日付の扱いは注意が必要です。

(IE11)
ISO日付形式ができていない
(Firefox)


(Chrome)



 【その他】
ロケート変換はいろいろできますので、覚えておきましょう
var date = new Date();
var options = {
    weekday: "long", year: "numeric", month: "short",
    day: "numeric", hour: "2-digit", minute: "2-digit"
};

date.toLocaleDateString("en-US")   -> 2/2/2015
date.toLocaleTimeString("en-us", options) -> MondayFeb,2,2015, 09:40 AM
date.toLocaleDateString("ja-JP") ->2015年2月2日
date.toLocaleTimeString("ja-JP", options) -> 2015年2月2日金曜日 09:40

【参考URL】
http://www.codeproject.com/Articles/870950/Expressing-Date-Time-Information-with-the-time-Ele

1 件のコメント:

  1. Yes, I completely understand your point of view; these qualifications are important for being an ecommerce development developer. You need to have a bachelor's degree in computer science or a related degree. Also, knowledge of the software development life-cycle is necessary. You should check out Eiliana.com; they help you find good projects according to your qualifications.

    返信削除