JS日期。你离你的百年纪念有多远?

时间:2018-03-11 12:23:34

标签: javascript date datetime

我遇到了setFullYear()的问题。在输入时,我有一些像1/1/1980这样的日期,我应该知道过去的时间有多久: 38岁1个月10天14小时13分钟。但问题在于如何才能获得到百年的时间?

我的解决方案:

var now = new Date()

var oldDate = new Date()

now.setFullYear(now.getFullYear() - parseFloat(year1), now.getMonth() - parseFloat(month1), now.getDate() - parseFloat(daynumber1), now.getHours(), now.getMinutes());* // now-oldDate*

oldDate.setFullYear(parseFloat(100) - now.getFullYear(), parseFloat(12) - now.getMonth(), parseFloat(30) - now.getDate(), parseFloat(24) - now.getHours(), parseFloat(60) - now.getMinutes());* //100years - (now-oldDate)*

问题是我不能减去或加上now.getHoursnow.getMinutes的任何内容。

2 个答案:

答案 0 :(得分:0)

只需将数据转换为timeinmillis并减去这些数字。

或者,如果您想减去或添加一年或一个月,只需减去相当于您的期间的时间,例如月份或一年

减去两个日期:

var now = new Date();

var oldData = new Date('date string in proper format');
//or set Year, month or day by yourself after creating the date object pointing to the current date.

var subtractedResult = now.getTime() - oldDate.getTime();
// now you have the diff in milliseconds 

//Milliseconds in a year = 31536000000

var diff in years = subtracted results / 31536000000;

同样,如果你愿意,你可以降低到单位秒数

答案 1 :(得分:-2)

function convertMS(ms) {
  var d, h, m, s;
  s = Math.floor(ms / 1000);
  M = Math.floor(s / 60);
  h = Math.floor(M / 60);
  d = Math.floor(h / 24);
  m = Math.floor(d / 30);
  y = Math.floor(m / 12);
  s %= 60;
  M %= 60;
  h %= 24;
  d %= 30;
  m %= 12;
  return {years:y,months:m,days: d, hours: h, minutes: M, seconds: s };
};
var diff = (new Date() - new Date(1980,0,1));
console.log(convertMS(diff))

V2:

<script>

function daysInMonth (month, year) {
    return new Date(year, month+1, 0).getDate();
}

function diffs(a,b){
    y=(a.getFullYear())-(b.getFullYear())
    m=(a.getMonth())-(b.getMonth())
    d=(a.getDate())-(b.getDate())
    h=(a.getHours())-(b.getHours ())
    M=(a.getMinutes())-(b.getMinutes())
    s=(a.getSeconds())-(b.getSeconds())
    if (s<0){s+=60;M-=1;}
    if (M<0){M+=60;h-=1;}
    if (h<0){h+=24;d-=1;}
    var dim=daysInMonth(a.getMonth(),a.getFullYear())
    while (d<0){d+=dim;m-=1;}
    if (m<0){m+=12;y-=1;}
    return {years:y,months:m,days: d, hours: h, minutes: M,seconds:s};
}

var t=new Date();
var t1=new Date(1980,0,1);
var diff = diffs(t , t1);
document.write(JSON.stringify(diff))

</script>  

<强>样品

var t=new Date('2018-07-01');
var t1=new Date('2018-05-31');
var diff = diffs(t , t1);
console.log(JSON.stringify(diff))

var t=new Date('2018-03-01');
var t1=new Date('2018-01-31');
var diff = diffs(t , t1);
console.log(JSON.stringify(diff))

var t=new Date('2016-03-01');
var t1=new Date('2016-01-31');
var diff = diffs(t , t1);
console.log(JSON.stringify(diff))  

<强>结果

{"years":0,"months":1,"days":1,"hours":0,"minutes":0,"seconds":0}
{"years":0,"months":1,"days":1,"hours":0,"minutes":0,"seconds":0}
{"years":0,"months":1,"days":1,"hours":0,"minutes":0,"seconds":0}