自打字脚本以来的客户持续时间以来如何计算客户

时间:2019-04-22 05:53:57

标签: javascript angular typescript

我想找出一个人成为客户多长时间了。 我的意思是我只是想从开始日期中减去当前日期。 但是我不明白我在做什么错。

customerStartDate: String;
currentDate: any = '';
this.customerStartDate = this.sampleData1.customerStartDate;    
this.currentDate = new Date();
// Get Customer Age
this.customerAge = this.currentDate.getTime() - this.customerStartDate.getTime();

但是当前年龄有误。 我该如何计算打字稿中的客户持续时间。

2 个答案:

答案 0 :(得分:1)

           customerStartDate: any;
            currentDate: any;
            this.customerStartDate = this.sampleData1.customerStartDate;    
            this.currentDate = new Date();
            // Get Customer Age in Days
var diff=this.currentDate.getTime() - new Date(this.customerStartDate).getTime()
            this.customerAge = this.calculateYears(diff/(24 * 60 * 60 * 1000)); //in Days


    calculateYears(){
    if (days < 0)
    {
        date2_UTC.setMonth(date2_UTC.getMonth() - 1);
        days += DaysInMonth(date2_UTC);
    }

    var months = date2_UTC.getMonth() - date1_UTC.getMonth();
    if (months < 0)
    {
        date2_UTC.setFullYear(date2_UTC.getFullYear() - 1);
        months += 12;
    }

    var years = date2_UTC.getFullYear() - date1_UTC.getFullYear();


    if (years > 1) yAppendix = " years";
    else yAppendix = " year";
    if (months > 1) mAppendix = " months";
    else mAppendix = " month";
    if (days > 1) dAppendix = " days";
    else dAppendix = " day";

    return years + yAppendix + ", " + months + mAppendix + ", and " + days + dAppendix + " old.";
    }

答案 1 :(得分:1)

首先,您应该将customerStartDate转换为Date对象:

this.customerStartDate = new Date(this.sampleData1.customerStartDate);   

然后,您将获得今天的日期和customerStartDate之间的差,以毫秒为单位。

this.currentDate = new Date();
this.customerAge = this.currentDate - this.customerStartDate;

如果您希望将其转换为可读的格式(显示日期,分钟等),则可以执行以下操作:

const convertToReadableTime = time => {
  const days = Math.floor(time / (24 * 60 * 60 * 1000));
  const daysMs = time % (24 * 60 * 60 * 1000);
  const hours = Math.floor((daysMs) / (60 * 60 * 1000));
  const hoursMs = time % (60 * 60 * 1000);
  const minutes = Math.floor((hoursMs) / (60 * 1000));
  const minutesMs = time % (60 * 1000);
  const seconds = Math.floor((minutesMs) / (1000));
  return `${days} days, ${hours} hours, ${minutes} minutes, and ${seconds} seconds`;
}

console.log(convertToReadableTime(736771945325));