Reputation: 375
how can I send current date to API using typescript in a specific format (DateTime) when I send date to API, it's sent in this format so I got the error.
my ts code:
date: Date;
constructor( private dataStorageService: DataStorageService) {
this.date = new Date();
}
onSubmit(Message , form : FormGroup){
let newMsg = {
username: Message.username,
header: Message.header,
content: Message.content,
file: Message.file
}
this.dataStorageService.postMessage(newMsg, this.Id , this.date).subscribe(data => {
console.log('done');
console.log(this.date);
}, error => {
console.error("Error saving jobs!");
})
}
http://api.azharcouncil.com/api/notification/PostNotification?user_id=15&Header=hj&Content=hjh&File_Path=null&date=Wed%20Nov%2015%202017%2010:44:56%20GMT+0200%20(Egypt%20Standard%20Time)
So my request is invalid because of the date format...
Upvotes: 4
Views: 20762
Reputation: 1609
Here is the complete answer to your question.
Import the DatePipe from in the main module and provide that to your main module in main.module.ts in your provider array like given below:
import {DatePipe} from '@angular/common';
providers: [DatePipe]
Use it in your ts file with these methods, also import DatePipe from @angular/common in your ts file as well.
import {DatePipe} from '@angular/common';
Then in your constructor initialize this:
constructor(private _http: HttpClient, public datepipe: DatePipe) { }
Now use these methods to get the correct date format:
let myDate = new Date();
console.log(this.datepipe.transform(myDate, 'yyyy-mm-dd'));
someDateVar = this.datepipe.transform(myDate, 'yyyy-mm-dd');
Now someDateVar can be used to send it to server which has the date format you need. Also note that you can use multiple other date formats as well which are given in the Angular date pipe documentation.
Upvotes: 7
Reputation: 821
we can achieve this by using moment.js
Sample coding
import * as moment from 'moment-timezone'
export enum dateFormats {
'DMY'= 'DD/MM/YYYY',
'MDY'= 'MM/DD/YYYY'
}
// converts datestring to date
export const ToDate = (dateString: string, format: string) => new Date(moment(dateString, format))
// converts date to datestring
export const ToDateString = (date: Date, format: string) => moment(date).format(format)
Usage (in component)
const dateValue = new Date() // Date = Tue Feb 19 2020 12:05:22 GMT+0530 (IST)
const dateString = ToDateString(dateValue, dateFormats.DMY) // dateString = '19/02/2020'
Upvotes: 0