Reputation: 1183
I am trying to get the date from the datepicker and save it in sql server but the output is coming like '1538107200000'. What format is it and how to convert it to a date format which is compatible with sql server date format.
in component.html
<input matInput [matDatepicker]="picker" placeholder="enter date"
(dateInput)="addEvent('input', $event)">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
in component.ts
addEvent(type: string, dinput: MatDatepickerInputEvent<Date>) {
this.dinput.push(`${dinput.value}`);
this.date = new Date(this.dinput[0].toString());
this.dates = moment(this.date, 'YYYY-MM-DD').toString();
console.log(this.dates);
}
this is giving error of invalid date. How to fix it? Please help.
Upvotes: 1
Views: 4915
Reputation: 1
You can use DatePipe too. Try this:
First Step, inject the DatePipe Provider on app.module.ts file:
import { DatePipe } from '@angular/common';
@NgModule({
...
providers: [
[DatePipe]
],
...
})
And to convert your data into the desired format:
import { DatePipe } from '@angular/common';
constructor(private datePipe: DatePipe) {}
this.datePipe.transform(this.myFormControl.value,'yyyy-MM-dd');
For more formats, follow the DatePicker documentation
Upvotes: 0
Reputation: 789
You are getting date in json format . Below is a custom filter to convert json date format to real date.
.filter("filterdate", function() {
var re = /\/Date\(([0-9]*)\)\//;
return function(x) {
var m = x.match(re);
if( m ) return new Date(parseInt(m[1]));
else return null;
};
});
After that add below filter in component.html
<input {{dateInput| filterdate | date:'dd/MM/yyyy'}}>
Upvotes: 0
Reputation: 534
1538107200000 is date in millisecond (epoch timestamp). To convert it into date object use new Date(1538107200000)
.
To get Date in desired format use moment(new Date(1538107200000)).format("YYYY-MM-DD")
. This will give you date in YYYY-MM-DD Format. Now you need to save this in SQL Server. This will go to your server as String, you need to find what date format your server supports and cast that string to date and save to DB.
Upvotes: 2
Reputation: 722
That is seconds since the epoc, see here. I believe you are not using the moment constructor correctly. Try this:
moment(this.date).format('YYYY-MM-DD').toString();
Either that or the value you are passing to the moment constructor is in a format that moment doesn't recognize. See the documentation.
Upvotes: 0