Angular 4今天和明天的日期

时间:2018-04-18 12:00:11

标签: angular typescript

我想得到2个变量。 1表示当前日期(yyyy-MM-DD),1表示明天(yyyy-MM-DD)。

我需要将这两个变量放在我的HTTP请求中。 有人可以告诉我如何制作2个变量并在我的HTTP请求中使用它们。 目前的代码是:

export class BookingService {

    private config: Object;
    public today = new Date();
    public tomorrow = new Date();
    public domainSettings: Object = {};

    constructor(
        private http: Http,
        private kioskservice: KioskService
    ) { }

    public getAllBookings() {
        return new Promise((resolve, reject) => {
            this.http
                .get(
                    `${this.kioskservice.getAPIUrl()}search/dashboard/${this.kioskservice.LocationGUID()}/?apikey=${this.kioskservice.getAPIKey()}&format=json&from=2018-04-17&until=2018-04-18&full=true`
                )
                .toPromise()
                .then(
                    res => {
                        this.config = res.json()
                        console.log(res.json());
                        resolve();
                    },
                    msg => {
                        throw new Error("Couldn't get all Bookings: " + msg);
                    }
                );
        });
    }
}

1 个答案:

答案 0 :(得分:1)

只需使用JavaScript的Date界面即可获得日期。

要将它们用于HTTP调用,只需使用模板字符串添加它们。

public getAllBookings() {
    // Get the dates
    const today =  new Date();
    const tomorrow =  new Date(today.setDate(today.getDate() + 1));

    return new Promise((resolve, reject) => {
      this.http
        .get(
          `${this.kioskservice.getAPIUrl()}search/dashboard/${this.kioskservice.LocationGUID()}/?apikey=${this.kioskservice.getAPIKey()}&format=json&from=${this.dateFormat(today)}&until=${this.dateFormat(tomorrow)}&full=true`
        )
        .toPromise()
        .then(
          res => {
            this.config = res.json()
            console.log(res.json());
            resolve();
          },
          msg => {
            throw new Error("Couldn't get all Bookings: " + msg);
          }
        );
    });
  }

  // Helper function to format if you don't use moment.js or something alike
  private dateFormat(date: Date) {
    const day = date && date.getDate() || -1;
    const dayWithZero = day.toString().length > 1 ? day : '0' + day;
    const month = date && date.getMonth() + 1 || -1;
    const monthWithZero = month.toString().length > 1 ? month : '0' + month;
    const year = date && date.getFullYear() || -1;

    return `${year}-${monthWithZero}-${dayWithZero}`;
  }

如果您要使用日期,时间戳等工作,那么使用moment.js之类的内容非常有用。