0

I have a typescript file used to export some constant variables (export const). I would like to use datepipe to format date in the ts file, but I do not know how to add service to use datepipe in a non component ts file.

For example:

export const dateObject = [
  {
    value: {
      start: new Date(),
      end: new Date().setFullYear(new Date().getFullYear() + 10),
    },
    title: 'Ten Years Later'
  }
];

How can I make datepipe.transform(, 'yyyy-MM-dd') work in this typescript?

Thank you!!

WenliL
  • 419
  • 2
  • 14
  • 1
    Does this answer your question? [Angular - Use pipes in services and components](https://stackoverflow.com/questions/35144821/angular-use-pipes-in-services-and-components) – R. Richards Nov 30 '21 at 23:17
  • not really, I know how to use datepipe in export class. But I would like to know how to use a service in export const. – WenliL Nov 30 '21 at 23:21
  • @WenliL That distinction is not relevant: to use a pipe virtually anywhere outside a template, you just import it and call its `.transform()` method. – msanford Nov 30 '21 at 23:32

2 Answers2

1
new DatePipe(navigator.language || 'en-US').transform(new Date(), 'yyyy-MM-dd')
prashant Jha
  • 221
  • 1
  • 7
0
import { DatePipe } from '@angular/common';

export const dateObject = [{
  value: {
    start: new DatePipe('en-US').transform(new Date(), 'yyyy-MM-dd'),
    end: new Date().setFullYear(new Date().getFullYear() + 10),
  },
  title: 'Ten Years Later',
}];
Damian
  • 1,084
  • 3
  • 14
  • 26