如何将字符串转换为日期在 Angular2类型?

我想创建一个新的 Date 对象,具有特定的日期。 我想过把它从一个特定的字符串转换过来,例如:

let dateString = '1968-11-16T00:00:00'

如何将其转换为日期对象 打字稿

更新:

我要求一个解决方案 在 Typescript,而不是在 Javascript,在 Angular2,而不是 AngularJS (1.x)

435088 次浏览

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

// variables used in html
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);


// format date in typescript
getFormatedDate(date: Date, format: string) {
const datePipe = new DatePipe('en-US');
return datePipe.transform(date, format);
}


// Convert date to user timezone
const localDate: Date = this.convertToLocalDate('01/01/2021');


convertToLocalDate(responseDate: any) {
try {
if (responseDate != null) {
if (typeof (responseDate) === 'string') {
if (String(responseDate.indexOf('T') >= 0)) {
responseDate = responseDate.split('T')[0];
}
if (String(responseDate.indexOf('+') >= 0)) {
responseDate = responseDate.split('+')[0];
}
}


responseDate = new Date(responseDate);
const newDate = new Date(responseDate.getFullYear(), responseDate.getMonth(), responseDate.getDate(), 0, 0, 0);
const userTimezoneOffset = newDate.getTimezoneOffset() * 60000;


const finalDate: Date = new Date(newDate.getTime() - userTimezoneOffset);
return finalDate > Util.minDateValue ? finalDate : null;
} else {
return null;
}
} catch (error) {
return responseDate;
}
}

In HTML:

\{\{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[\{\{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[\{\{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[\{\{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[\{\{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[\{\{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[\{\{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[\{\{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[\{\{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[\{\{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[\{\{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[\{\{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[\{\{todayDate | date:'MMMM yyyy'}}]</option>
</select>