0

I have a couple of date fields in my app. So i need to send date as time-stamp to the database .So I'm planning to write a custom pipe to modify the model value . Will that befit to my need ? or do I need to write custom directive for this ?

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'capitalize'})
export class CapitalizePipe implements PipeTransform {
  transform(value: string, args: string[]): any {
    if (!value) return value;

    return value.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
  }
}
AhammadaliPK
  • 3,448
  • 4
  • 21
  • 39
  • I'd suggest to explain your case. *need to send date as time-stamp to the database* - what does it have to do with the question? Do you intend to modify the date with a pipe for that? Neither a directive nor a pipe are suitable for that. – Estus Flask Dec 22 '17 at 07:27
  • yes , I will change the model value with directive or pipe ,So that I can send time stamp to db , but the actual date will be showed to user, I'm intended to so, – AhammadaliPK Dec 22 '17 at 08:24

2 Answers2

2

You have it backward. In Angular, pipes are used in the template to show data in a more appropriate way. They are not there to modify your actual data.

I recommend using the ng-bootstrap library (you can find it on Github) to use a proper calendar widget. The model can be configured to return a timestamp.


Edit: Adding example of calling it in the code:

let name = new UserNamePipe().transform(user);

https://stackoverflow.com/a/35159546/5885595

Simon S.
  • 101
  • 1
  • 2
  • Can Pipes only be used in template? – Mahi Dec 22 '17 at 07:51
  • Pipes typically should be reserved for templates, but I've found that it's sometimes convenient to call them in the TS file as well. Consider that they are simple classes that have a method called "transform". See answer for example. – Simon S. Dec 23 '17 at 09:18
0

Hope I understood your question right.
For conversion you can use standard DatePipe (or extend it), for example:

{{ dateField | date:'HH:mm:ss SSS'}}
{{ dateField | date:'HHmmssSSS':'+0000'}}