多个日期对象比较无法按预期工作

时间:2015-10-25 15:36:00

标签: javascript

试图找出我的日期对象值未正确比较的原因。相同的'GREATER than'字符串被附加到'review-full-review-comment-wrap'块...我的比较dateObjects值的方法是否正确?

<div class="review-full-review-single-wrap">
    <div class="review-full-stars">
        <span class="review-full-timestamp">
            <time itemprop="datePublished" datetime="2014-07-29T11:25:47-07:00">July 29, 2014</time>
        </span>
    </div>

    <div class="review-full-review-comment-wrap"></div>
    ////*Append LESS THAN*////
</div>

<div class="review-full-review-single-wrap">
    <div class="review-full-stars">
        <span class="review-full-timestamp">
            <time itemprop="datePublished" datetime="2015-05-05T05:50:05-07:00">May 5, 2015</time>
        </span>
    </div>

    <div class="review-full-review-comment-wrap"></div>
    ////*Append GREATER THAN*////
</div>

function runProgram(){

    var elems = document.getElementsByClassName("review-full-timestamp");

    for (var i = 0; i < elems.length; i++) {
        var timeElems = document.getElementsByTagName("time");
        var dateString = Date.parse(timeElems[i].innerHTML);
        var dateObj = new Date(dateString);
        var startDate = "May 6, 2015";
        var startDateObj = new Date(startDate);
    }

    if(dateObj > startDateObj){
        $('.review-full-review-comment-wrap').append('<p>GREATER than</p>');
    } else {
        $('.review-full-review-comment-wrap').append('<p>LESS than</p>');
    }

}
runProgram();

3 个答案:

答案 0 :(得分:2)

基于@Bergi上面的评论:这是正确的函数

var startDate = new Date( 'May 6, 2015' );
$( '.review-full-review-single-wrap' ).each( function( i, e ) {
    var dateObj = new Date( Date.parse( $( e ).find( '.review-full-timestamp > time' ).attr( 'dateTime' ) ) );
    var div = $( e ).find( '.review-full-review-comment-wrap' );
    if ( dateObj.getTime() >= startDate.getTime() ) {
        div.append( '<p>dateObj is GREATER than startDate</p>' );
    } else {
        div.append( '<p>dateObj is LESS than startDate</p>' );
    }
} );

答案 1 :(得分:0)

请参阅getTime()

根据您的代码考虑以下示例:

        var dateString = Date.parse('10-23-2015');
        var dateObj = new Date(dateString);
        var startDate = "May 6, 2015";
        var startDateObj = new Date(startDate);

        if(dateObj.getTime() > startDateObj.getTime()){
            console.log('cool');
        }

此输出

  

凉爽

如您所见,10-23-2015 大于May 6, 2015

答案 2 :(得分:-1)

尝试将27, 3添加到每个日期对象,将日期值推送到数组,使用49, 7确定.getTime()元素之一Array.prototype.some()是否已解析为time } objects大于html

&#13;
&#13;
Date
&#13;
startDateObj
&#13;
&#13;
&#13;