我正在使用角材料日期选择器 https://material.angular.io/components/select/overview
但这仅返回日期而不是当前时间: 2018 年 5 月 28 日星期一 00:00:00 GMT+0530 (IST)
有什么方法可以从中获取当前时间吗?
您可以使用 ngModelChange 来解析日期,然后再将其设置为您的模型,我推荐您使用 momentJS 来轻松进行日期操作。
在 HTML 中
<input [ngModel]="date" (ngModelChange)="onDataChange($event)" matInput [matDatepicker]="picker" placeholder="Choose a date">
在你的 Component.ts 中
onDataChange(newdate) {
const _ = moment();
const date = moment(newdate).add({hours: _.hour(), minutes:_.minute() , seconds:_.second()})
this.date = date.toDate();
console.log({hours: _.hour(), minutes:_.minute() , seconds:_.second()})
}
您可以在这里找到完整的解决方案https://stackblitz.com/edit/angular-ecq2lc
目前,材料日期选择器仅提供当前日期(没有当前时间),但官方存储库中存在一个未解决的问题,因此我们可能会在不久的将来看到时间选择器。
角度材质现在不提供时间,您需要手动从时间戳获取时间,试试这个 -
function getTimeFromDate(timestamp) {
let date = new Date(timestamp * 1000);
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
return hours+":"+minutes+":"+seconds
}
let timeStamp = new Date("Mon May 28 2018 00:00:00 GMT+0530 (IST)")
console.log(getTimeFromDate(timeStamp));
For Example currenttime = Mon May 28 2018 00:00:00 GMT+0530 (IST)
Currenttime is an example if u using current date means just use new Date()
//Sample function calling Method
Exacttime(){
this.functionName = this.diffhours(new(currenttime))
}
diffhours(currenttime){
var diff = new Date(currenttime);
diff .getHours(); // => 9
diff .getMinutes(); // => 30
diff .getSeconds(); // => 51
}
这对我有用
在我的例子中是选择任何日期,但小时时间是当地的
public selectDate(event: MatDatepickerInputEvent<Date>) : void
{
if(event.value)
{
const dtPicker = new Date(event.value);
dtPicker.setHours(new Date().getHours());
dtPicker.setMinutes(new Date().getMinutes());
dtPicker.setSeconds(new Date().getSeconds());
this.dtInputValue = dtPicker;
}
}