从1开始将对象转换为日期

时间:2019-06-08 08:42:59

标签: angular typescript date datepicker bootstrap-4

我已将angular bootstrap datepicker组件添加到我的应用中,当我选择日期时,我收到一个看起来像{year: 1993, month: 8, day: 9}的对象,我想将其转换为Date宾语。一切都很好,但是转换为日期后,整个日期都移动了:1993-09-08T22:00:00.000Z。您知道日期转换仍具有相同日期的任何技巧吗?

我已经调查了由于开始日期数字而引起的问题。在角度引导程序中,它从1开始,但在日期对象中,它从0开始。

HTML:

<div class="col-md-12 mb-3 form-group">
    <label for="dateOfBirth">Data urodzenia</label>

    <input class="form-control"
        placeholder="yyyy-mm-dd" id="dateOfBirth" 
        formControlName="dateOfBirth"
        name="dp"
        ngbDatepicker
        #d="ngbDatepicker"
        (click)="d.toggle()" 
        [minDate]="fromDate"
        [maxDate]="toDate">

    <span class="input-group-addon">
        <i class="glyphicon glyphicon-calendar"></i>
    </span>

    <ngb-alert [type]="'danger'"
        [dismissible]="false" 
        class="form-alert"
        *ngIf="envelopeCreationFrom.controls.dateOfBirth.touched && 
        envelopeCreationFrom.controls.dateOfBirth.errors?.required">
        Error
    </ngb-alert>
</div>

打字稿:

 console.log(dateOfBirth);
 console.log(new Date(dateOfBirth['year'], dateOfBirth['month'], dateOfBirth['day']));
 console.log(new Date(dateOfBirth['year'], dateOfBirth['month'], dateOfBirth['day']).toISOString());
 console.log(new Date(dateOfBirth['year'], dateOfBirth['month'], dateOfBirth['day']).toDateString());

1 个答案:

答案 0 :(得分:1)

如果您的日期案例包含任何类型的计算或日期格式等,我建议使用moment.js。

您需要先安装一下。

npm install moment --save

只需将其导入您需要的组件中即可。

import * as moment from 'moment';