【问题标题】:Typescript - Calculate months and years from current date [duplicate]打字稿 - 从当前日期计算月份和年份[重复]
【发布时间】:2018-09-21 13:08:18
【问题描述】:

我的应用程序中的每个用户都有一个出生日期。例如。格式为29/01/2015

我目前的代码从今天的日期和提供的出生日期计算年份:

((new Date((new Date().getTime() - new Date(user.dob).getTime())).getFullYear()) - 1970)

对于上面的示例,这将检索号码 3,因为距离 29/01/2015 已经三年了。

如果年份低于1,获取月份的最佳优化是什么?

例如对于这个日期:21/03/2018,我的代码将返回 0,因为一整年还没有过去。如何优化我的逻辑来检索6 months,即今天(21/09/2018)和21/03/2018之间的时间?

P.S.我想避免使用任何库。

【问题讨论】:

  • 没有真正的理由不使用像 momentjs 这样的库。事实上,我什至认为最好使用一个。它已经过试验和测试,它绝对有效。很可能您将添加更多的日期操作和格式设置,这意味着如果您使用 vanilla js,您将添加越来越多的已经被弄清楚和处理的功能。而且以后很难替换。
  • 您没有正确解析日期,并且使用 Date 构造函数来计算年差是一个很差的近似值。有很多关于如何做到这两点的现有答案。

标签: javascript angular typescript date


【解决方案1】:

我会使用momentjs 是一个很酷的库,用于与日期时间相关的东西。无论如何我的方法是 - 计算月份 - 然后检查超过 12 的月份,然后我从月份中获取年份 - 除非显示月份

有瞬间:Live sample with moment

let months = moment('2011-06-11').diff(moment('2011-04-11'), 'month', true);

if (months >= 12) {
    console.log('years:', (months - (months %12))/12 );
} else {
    console.log('only months', parseInt(months));
}

纯js:Live sample with pure JS

let dateFrom = new Date('2011-04-11');
let dateTo = new Date('2011-06-11');

let months = dateTo.getMonth() - dateFrom.getMonth() + (12 * (dateTo.getFullYear() - dateFrom.getFullYear()));

if (months >= 12) {
    console.log('years:', (months - (months %12))/12 );
} else {
    console.log('only months', parseInt(months));
}

【讨论】:

  • 虽然这肯定会为我完成这项工作,但您认为没有 MomentJS 是否有可能做到这一点?我真的不希望仅仅为了这样的小事而在我的项目中添加一个新库。
  • 我添加了有和没有时刻@IamOptimus
【解决方案2】:

我最近在我的一个项目中使用了下面的代码,它可以工作。请注意,我也在使用momentjs,它是免费和开源的,可供下载和使用。

这里是示例 jsfiddle 链接http://jsfiddle.net/n70vdz1k/

var dob = "13-05-1981";
mdob = moment(dob, 'DD-MM-YYYY'); // date of birth
if (!mdob.isValid()) {
    alert("Invalid date format");
    return;
}
targetDate = moment(); //this will give today's date
months = targetDate.diff(mdob, 'months');
let years = parseInt(months / 12);
let balanceMonths = months % 12;
let days;
if (!balanceMonths) {
    months = 0;
   // days = targetDate.diff(mdob, 'days');
    dob_date = mdob.date();
    target_month = targetDate.month();
    construct_date = moment().month(target_month).date(dob_date);
    days = targetDate.diff(construct_date, 'days');
    if(days < 0){
        days = 30 + days;
    }
} else {
    months = balanceMonths;
    dob_date = mdob.date();
    target_month = targetDate.month();
    construct_date = moment().month(target_month).date(dob_date);
    days = targetDate.diff(construct_date, 'days');
     if(days < 0){

        days = 30 + days;
    }
}

console.log("months", months)
console.log("years", years)
console.log("days", days)

【讨论】:

    【解决方案3】:

    您可以简单地自己计算差异:

    function diffYears(d) {
      return Math.floor((Date.now() - new Date(d)) / 12 / 30 / 24 / 3600 / 1000);
    }
    
    function diffMonths(d) {
      return Math.floor((Date.now() - new Date(d)) / 30 / 24 / 3600 / 1000);
    }
    
    console.log(diffMonths('2018-03-21'), diffYears('2018-03-21'));
    console.log(diffMonths('2017-03-21'), diffYears('2017-03-21'));
    console.log(diffMonths('2016-03-21'), diffYears('2016-03-21'));

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 2013-02-15
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 2016-04-05
      • 2015-03-27
      相关资源
      最近更新 更多