0

The date format which I am getting from the Api response is like this.

"startDate" : "07112018 00:00".

I want to convert this to in dd-mm-yyyy HH:mm format. that is like this 07-11-2018 00:00. Can anyone please tell me how to do this using Angular 6.

mruanova
  • 6,351
  • 6
  • 37
  • 55
ananya
  • 1,001
  • 6
  • 33
  • 50

2 Answers2

1

You can use DatePipe API for this: https://angular.io/api/common/DatePipe

@Component({
 selector: 'date-pipe',
 template: `<div>
   <p>Today is {{today | date}}</p>
   <p>Or if you prefer, {{today | date:'fullDate'}}</p>
   <p>The time is {{today | date:'h:mm a z'}}</p> //format in this line
 </div>`
})
// Get the current date and time as a date-time value.
export class DatePipeComponent {
  today: number = Date.now();
}

and this is what actually you want:

{{myDate | date: 'dd-MM-yyyy'}}

Edit: Using built-in pipe in component,

import { DatePipe } from '@angular/common';

class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
}

Please read this topic, I took example from there: https://stackoverflow.com/a/35152297/5955138

Edit2: As I described in comment, you can substring your date using this.

var str = '07112018'
var d = new Date(str.substring(0, 2)+'.'+str.substring(2, 4)+'.'+str.substring(4, 8));

Output: Wed Jul 11 2018 00:00:00 GMT+0300

rcanpahali
  • 2,565
  • 2
  • 21
  • 37
  • But i want to convert that and get the value in .ts file. Not in html file. How to do that in .ts file @shadowman_93 – ananya Jan 18 '19 at 14:09
  • Can you please give detailed information, what do you get as error ? – rcanpahali Jan 18 '19 at 14:35
  • Yes, this error i am getting. InvalidPipeArgument: 'Unable to convert "02112018 00:00" into a date' for pipe 'DatePipe' – ananya Jan 18 '19 at 14:37
  • i am doing like this. var startdate = this.datePipe.transform('02112018 00:00', 'dd-mm-yyyy HH:mm'); console.log("startdate"+ startdate); – ananya Jan 18 '19 at 14:38
  • Can you tell me if "07112018 00:00" this is correct format of sending data ? – ananya Jan 18 '19 at 15:12
  • @ananya that does not look like a valid date format. You can try using `new Date('02112018 00:00')` to verify. You should provide the date in a valid format. – Seiyria Jan 19 '19 at 00:12
  • @ananya I've updated my answer as Seiyria told above. – rcanpahali Jan 21 '19 at 08:54
0

try this function to convert time format as you require

timeFormetChange(){
 var date =new Date();
 var newDate = date.getDate();
 var newMonth = date.getMonth();
 var newYear =date.getFullYear();
 var Hour = data.getHours();
 var Minutes = data.getMinuets();
 return `${newDate}-${newMonth }-${newYear} ${Hour}:${Minutes }`
}
code_Red
  • 1
  • 2