0

日付が今日より前かどうかを確認したい。もしそうなら、私は日付を表示したいが、それが今日なら、私は日付ではなく時間を表示したい. 私がチェックしている日付は dd-mm-yyy hh:mm 形式であるため、比較されません。

私がこれまでに持っているものを見てください:

var created = '25-05-2012 02:15';
var now = new Date();

if (created < now) { 
  created_format = [ format the date to be 25-05-2012 ]
} else {
  created_format = [ format the date to be 02:15 ]
}

他の例でこれらを使用now.dateFormat()してnow.format()みましたが、「関数ではありません」というエラーメッセージが表示されます。

4

2 に答える 2

1

日付文字列の一部を取得することから始めます。

var created = '25-05-2012 02:15';
var bits = created.split(/[-\s:]/);
var now = new Date(); 

// Test if it's today    
if (bits[0] == now.getDate() &&
    bits[1] == (now.getMonth() + 1) &&
    bits[2] == now.getFullYear() ) {

  // date is today, show time

} else {
  // date isn't today, show date
}

もちろん他にも方法はありますが、上記が一番簡単だと思います。例えば

var otherDate = new Date(bits[2], bits[1] - 1, bits[0]);
now.setHours(0,0,0,0);
if (otherDate < now) {
  // otherDate is before today
} else {
  // otherDate is not before today
}

getFullYear同様に、文字列を日付に変換すると、 , getMonth,を使用getDateして相互に比較できますが、これは基本的に最初のアプローチと同じです。

于 2012-05-28T10:12:01.447 に答える
0

getTimeメソッドを使用してタイムスタンプを取得できます。次に、それを現在の日付のタイムスタンプと比較できます。

于 2012-05-28T09:57:29.483 に答える