2017-10-30 5 views
0

moment.jsを使用してhours & minutesの形式の2つの日付を追加しようとしています。しかし結果はinvalidです。モーメントを使用して時間が分の場合は2回追加します.js

$(document).ready(function() { 
 
    $(".table-class").each(function() { 
 
    var total = 0; 
 
    $(this).find(".timeClass").each(function() { 
 

 
     var value = $(this).val(); 
 

 
     var start = moment(value, 'h:mma'); 
 
     console.log(start); 
 
     total += start; 
 

 
    }); 
 
    $(".total").text(moment(total, 'h:mma')); 
 
    }); 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table class="table-class"> 
 

 
    <tr> 
 
    <td> 
 
     <input type="text" value="1 hour 30 mins" class="timeClass"> 
 
    </td> 
 

 
    </tr> 
 
    <tr> 
 
    <td> 
 
     <input type="text" value="3 hours 02 mins" class="timeClass"> 
 
    </td> 
 

 
    </tr> 
 
</table> 
 
<p class="total"> 
 

 
</p>

任意の提案、ありがとうございください!

答えて

1

まず入力を解析して(例えば1時間30分)、の代わりに'h:mma'を使用する必要があります。ドキュメントのEscaping charatersセクションを参照してください。とにかくこれは回避策です。「1時間30分」と「3時間02分」の可能性が高いのは、特定の瞬間を表すものではないからです。

Defaultとしてセクション状態、momentjs:

だけ時間、分、秒、ミリ秒単位では、現在の日の瞬間を作成しているので、moment(value, 'h [hour] mm [mins]');を使用して

を渡され、今日にデフォルト設定。 diff()を使用して、1日の開始からのミリ秒数を取得できます。

最後にtotal変数からmoment.duration(Number)を使用してdurationオブジェクトを作成できます。瞬間持続時間の値は、hours()minutes()を使用するか、またはformat()メソッドmoment-duration-formatプラグインを使用して表示できます。ここで

ライブのサンプル:

$(document).ready(function() { 
 
    $(".table-class").each(function() { 
 
    var total = 0; 
 
    $(this).find(".timeClass").each(function() { 
 
     var value = $(this).val(); 
 

 
     var start = moment(value, 'h [hour] mm [mins]'); 
 
     var diff = start.diff(start.clone().startOf('d')); 
 
     total += diff; 
 

 
    }); 
 
    var dur = moment.duration(total); 
 
    $(".total").text(dur.hours() + ':' + dur.minutes()); 
 
    // Using moment-duration-format: 
 
    //$(".total").text(dur.format('h:mm')); 
 
    }); 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script> 
 

 
<table class="table-class"> 
 
    <tr> 
 
    <td> 
 
     <input type="text" value="1 hour 30 mins" class="timeClass"> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td> 
 
     <input type="text" value="3 hours 02 mins" class="timeClass"> 
 
    </td> 
 
    </tr> 
 
</table> 
 
<p class="total"></p>

+1

が助けをどうもありがとうございます:) – 06011991

関連する問題