6

Till now I was using momentjs library like this:

import * as moment from 'moment'; // import moment.
@Component({..});
export class TestClass {
  lastUpdated = Date
  constructor(private myService: MyService){
    this.lastUpdated = this.getCurrentTime(); **// this shows error.. that type string is not assignable to type 'Date'**
  }
 var getCurrentTime(){
    return moment().format('DD MMM YYYY HH:mm:ss'); 
 }
}

Above code shows me this error: that type string is not assignable to type 'Date'**

But same code exactly working fine when I use this line in place of the import module, evenn other resturent os

declare var moment: any;

But I canot use above statement as it is using "var": and 'any' is not suggested by Lint.

Why getCurrentTime is returning String? Should not this return Date

4
  • Change lastUpdated = Date to lastUpdated: moment() Commented May 17, 2017 at 19:20
  • sorry change it to lastUpdated = moment(); Commented May 17, 2017 at 19:35
  • 1
    getCurrentTime() returns a string b/c moment's format() method returns a string. momentjs.com/docs/#/displaying/format Commented May 17, 2017 at 20:31
  • The whole purpose of format is to return formatted string. What would 'formatted Date' look like? Commented May 17, 2017 at 21:08

2 Answers 2

9

“type string is not assignable to type 'Date'”

lastUpdated = Date should be lastUpdated: string.

Code

Fixed a few other things as well:

import * as moment from 'moment'; // import moment.
@Component({..});
export class TestClass {
  lastUpdated: string;
  constructor(private myService: MyService){
    this.lastUpdated = this.getCurrentTime();
  }
 getCurrentTime(){
    return moment().format('DD MMM YYYY HH:mm:ss'); 
 }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Can avoid calling one more function by the below code


import * as moment from 'moment'; // import moment.
@Component({..});
export class TestClass {
  lastUpdated: string;
  constructor(private myService: MyService){
    this.lastUpdated = moment(this.lastUpdated).format('DD MMM YYYY HH:mm:ss');
  }
}

1 Comment

I think moment(this.lastUpdated) should be moment().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.