日付を表す 8 桁の文字列があります。例えば:
20120515
この方法で作成された今日の日付と比較したいと思います。
var currentDate = new Date();
currentDate と比較するために、「8 桁の日付文字列」を適切な日付形式に変換するにはどうすればよいですか?
日付を表す 8 桁の文字列があります。例えば:
20120515
この方法で作成された今日の日付と比較したいと思います。
var currentDate = new Date();
currentDate と比較するために、「8 桁の日付文字列」を適切な日付形式に変換するにはどうすればよいですか?
substringメソッドを使用し、4つの要素をsubstringして、その年の新しい日付に割り当てます。次に、一度に2つの要素を部分文字列で囲み、それに応じて月と日付を格納します。
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
これで、2つの日付を通常の演算子と比較できます。
小さな日付ライブラリが必要な場合は、moment.jsを使用できます。
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM