使用开始日期,如何从 class 中的 javascript 中的开始日期中取出给定日期以输出年数

Using a start date, how to take away a given date from the start date in javascript in a class to output amount of years

开始使用 javascript 并被分配了一个任务来创建一个 getter 方法来计算和 returns 客户成为客户的年数。

但是我不知道如何在 getter 方法中存储 'customers' 开始日期。然后我不确定如何将这些日期的差异转换为年数。

如有帮助将不胜感激!

这是我正在处理的一段代码:

  class Customer extends Person{
constructor(id_number, first_name, last_name, email_address, customer_start_date){
super(id_number, first_name, last_name);
this.email_address = email_address;
this.customer_start_date = customer_start_date;



  }
  get email_address(){
    return this.email_address;
  }
  get customer_start_date(){
    customer_start_date = new Date(2018, 11, 22);
    return this.customer_start_date;
  }

}

let s2 = new Staff(123577, "Steve", "Smith", "stevesmith@work.com", (2018, 11, 22));
console.log(s2.first_name , "has been a customer for this many years: ", s2.customer_start_date);

开始日期可以存储为客户的 属性。该值可能是像“2016-07-23”这样的字符串或像 1469232000000 这样的时间值或任何最适合后端存储的值。我很想把所有事情都作为 UTC 来避免时区和 DST 混淆。

请注意,内置解析器应将“2016-07-23”视为 UTC,请参见Why does Date.parse give incorrect results?

下面是一个简单的例子来说明这个概念。

class Person {
  constructor (id, firstName, lastName) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

class Customer extends Person {
  constructor (id, firstName, lastName, startDate) {
    super(id, firstName, lastName);
    this.startDate = startDate;
  }
  
  // Simplistic example, production function should be much more sophisticated
  get customerYears() {
    return Math.round((Date.now() - new Date(this.startDate)) / (365.25 * 8.64e7));
  }
}

let p = new Customer(0, 'Pete', 'Smith', '2017-01-16');

console.log(`${p.firstName} has been a customer since ${p.startDate}, which is about ${p.customerYears} years.`);

customerYears 方法有意简化,您应该使用适合 Difference between two dates in years, months, days in JavaScript 的方法或包含日期算术函数的库。