我是代码新手,请原谅我这个问题的答案是否明显!
我正在从API收集JSON数据,我有一个值ExpectedDateTime,我想用它来计算 now 的分钟数和秒数。
格式为:2016-05-09T12:26:26
我试过这个:
function applyTimeToVallingby(data) {
$scope.timeToVallingby = 0;
$scope.timeToVallingby2 = 0;
d = new Date();
for(i=0;i<data.ResponseData.Buses.length;i++){
if(data.ResponseData.Buses[i].JourneyDirection === 2){
if($scope.timeToVallingby===0){
$scope.timeToVallingby=(d-data.ResponseData.Buses[i].ExpectedDateTime);
}else if($scope.timeToVallingby!=0&&$scope.timeToVallingby2===0){
$scope.timeToVallingby2=d-data.ResponseData.Buses[i].ExpectedDateTime;
}
}
}
}
但它不起作用。我试图找到一种方法将新的Date()值转换为类似于ExpectedDateTime的格式,这样我就可以减去,但是还没有能够。
致以最诚挚的问候,
答案 0 :(得分:2)
时间的差异:
var date = new Date('2016-05-09T12:26:26');
var now = new Date();
alert(" Seconds from now : " + parseInt( (now.getTime() - date.getTime())/1000 ) );
以你的方式 - d.getTime() - new Date( data.ResponseData.Buses[i].ExpectedDateTime).getTime()
答案 1 :(得分:0)
也许您可以使用Moment.js库:
$scope.daysLeft = function (end_date) {
var now = moment();
var then = moment(end_date);
var diff = then.diff(now, 'days');
if(diff <= 0)
return 0;
return diff;
}
答案 2 :(得分:0)
您需要先将ExpectedDateTime转换为日期对象
var expectedDateTime = "2016-05-09T12:26:26";
var items = expectedDateTime.split("T");
var dates = items[0].split("-");
var times = items[1].split(":");
var expectedDateObj = new Date( dates[0], dates[1]-1, dates[2], times[0], times[1], times[2] );
现在简单地获取与now
和此expectedDateObj
对象
var now = new Date();
var noOfMS = now.getTime() - expectedDateObj.getTime();
var numberOfSeconds = noOfMS/1000;
var noOfMinAndSec = "Min = " + numberOfSeconds/60 + " Sec = " + numberOfSeconds%60;
<强>样本强>
var expectedDateTime = "2016-05-09T12:26:26";
var items = expectedDateTime.split("T");
var dates = items[0].split("-");
var times = items[1].split(":");
var expectedDateObj = new Date( dates[0], dates[1]-1, dates[2], times[0], times[1], times[2] );
var now = new Date();
var noOfMS = now.getTime() - expectedDateObj.getTime();
var numberOfSeconds = Math.floor(Math.abs(noOfMS/1000));
var noOfMinAndSec = "Min = " + parseInt(numberOfSeconds/60) + " Sec = " + numberOfSeconds%60;
alert( noOfMinAndSec );
&#13;