【问题标题】:Angular 7, subtract calendar days from date inputAngular 7,从日期输入中减去日历天数
【发布时间】:2018-10-25 17:03:17
【问题描述】:

在这个 Angular 7 应用程序中,用户需要从日历输入中选择一个日期,然后生成 40 天前的日期。我无法在 Typescript 中弄清楚这一点。有很多 JavaScript 解决方案,但我不知道如何将它们转换为对 Angular 友好的打字稿版本。现在我有两个函数都试图做到这一点(生成 1 和生成 2),但都不起作用。

Generate 1 假设使用我导入的 'add-subtract-date' (npm),但我收到 Typescript 错误...“错误 TS2580:找不到名称 'require ’。”

Generate 2 没有错误,只是什么都不做。
我也不认为我的 HTML 是正确的。我对任何新想法持开放态度,只需将 HTML 也包括在内。

component.ts...

import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';
import { CalculatorService } from '../calculator.service';
import { add, subtract } from 'add-subtract-date';
import { NgForm } from '@angular/forms';


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  lastWorkingDay: any;
  isWeekday: string;

  public fortyDaysDate: any;



    private _retireSet: Date;
   get retireSet(): Date {
    return this._retireSet;
   }
   set retireSet(value: Date) {
    this._retireSet = value;

  }


  constructor(private calculatorService: CalculatorService) { 
  } 

  ngOnInit() {

  }


//Generate 1, this worked when using "const d: Date = new Date()"
public daysForty(): any {
  const d: Date = this.retireSet;
  const fortyDaysBack = subtract(d, 40, "days");
  this.fortyDaysDate = fortyDaysBack; 
}


// Generate 2, this does not work
  protected generateLastWorkingDay(): Date {
    const lastWorkingDay = new Date(Date.now()); 
    while(!this.isWorkingDay(lastWorkingDay)) {
      lastWorkingDay.setDate(lastWorkingDay.getDate()-40);
    }    
    return lastWorkingDay;
  }    
  private isWorkingDay(date: Date) {
    const day = date.getDay();
    const isWeekday = (day > 0 && day < 6);
    return isWeekday; 
  }





}

component.html...

  <form>
        <div class="container">

        <div class="form-group">
            <label for=""retireSet"">Set Date</label>
            <input type="datetime-local" id=""retireSet"" 
      name="RetireCalculatorSetDate" value="retireSet" ngModel 
      #RetireCalculatorSetDate="ngModel" [(ngModel)]="retireSet" class="form-control" />
        </div>

        <div class="form-group">
            <label for="staffID">Staff ID</label>
            <input type="text" id="staffID" name="RetireCalculatorStaffID"
                   [(ngModel)]="RetireCalculatorStaffID" 
                class="form-control" /> 
</div>


        <div>
                <button type="button" class="btn btn-success"
                        (click)="daysForty()">Generate 1</button>       
                <input type="text" name="RetireCalculatorDay45" value="fortyDaysDate" ngModel #RetireCalculatorDay45="ngModel" 
                [(ngModel)]="fortyDaysDate" class="form-control" />        
        </div>

        <div>
            <button type="button" class="btn btn-success" (click)="generateLastWorkingDay()"> Generate 2 </button>    
            <input type="date" class="text-field w-input" name="LastWorkingDay" 
                   value="LastWorkingDay" [(ngModel)]="LastWorkingDay" />
        </div>


        <button type="button" class="btn btn-success"  (click)="sendForm($event)">Submit</button>

        </div>
        </form>

【问题讨论】:

  • TypeScript 是 JavaScript。为什么不能使用 JS 版本?
  • 当我尝试在 Visual Studio Code 中输入 JS 时,出现错误。然后我不确定如何访问 HTML 中的 JS 结果。我仍然是 Jr. Dev(如果你没有注意到的话)。感谢您的任何建议。
  • 什么样的错误?你能用有问题的代码编辑你的问题吗
  • 我也推荐使用momentjs [momentjs.com/]

标签: angular typescript angular7


【解决方案1】:

您错误地使用了导入。请记住,您导入的是函数而不是对象。

import { add, subtract } from 'add-subtract-date';
...

//Generate 1
public daysForty(): Date {
  const d: Date = new Date();
  const fortyDaysBack = subtract(d, 40, "days"); // Check this. does subtract() manipulate "d" or create a new date?
  return fortyDaysBack;
}

您的第二个功能有点混乱。函数名称表明它将生成 LastWorkingDay。但是,逻辑与 while 循环混淆。

【讨论】:

  • 谢谢你确实摆脱了编译错误。但我不知道如何在我的 HTML 中显示结果。我在输入 [(ngModel)] 中有“fortyDaysBack”,并且在单击按钮时调用了函数。我想要输入字段中的结果。这个函数不应该使用今天的当前日期吗?
  • 我会将日期打印为字符串。这是我在互联网上找到的一个可以提供帮助的功能。 [免责声明]我没有测试过这个。 function formatDate(date) { var monthNames = [“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”,“八月”,“九月”,“十月”, “十一月十二月” ]; var day = date.getDate(); var monthIndex = date.getMonth(); var year = date.getFullYear();返回日期 + ' ' + monthNames[monthIndex] + ' ' + year; } console.log(formatDate(new Date())); // 在控制台中显示当前日期时间
  • 如果您要经常处理日期,我强烈建议您使用专门为此而设计的库。我唯一用过的就是momentJs
  • “d”和“fortyDaysBack”的值计算正确,但是在函数中的return语句之后,它们没有值。同样,我无法让值显示在 HTML 中。
  • 在您的代码中,您使用 (click) 事件调用 daysForty(),然后将变量返回给事件处理程序。您还可以在 daysForty() 方法中使用 addSubtractDate 作为定义的 const,该 const 超出了 html 的范围,并且在 ngModel 中不起作用。将 addSubtractDate 设为类范围内的公共变量并为其赋值,而不是从 daysForty() 方法返回。
猜你喜欢
  • 2021-12-31
  • 2012-04-29
  • 1970-01-01
  • 2012-10-07
  • 1970-01-01
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
  • 2020-01-13
相关资源
最近更新 更多