Reputation: 1829
Expected Output: 01-2019 or 02-2019 in string.
I need this in my Angular .ts file. Not in the HTML view file.
Upvotes: 2
Views: 52417
Reputation: 6759
You can use Date():
this.curdate = (new Date().getMonth() + 1).toString() + '-' + new Date().getFullYear().toString();
Note that new Date().getMonth()
start from 0 to 11 so you need to +1 to make it 1 to 12.
To add leading 0 based on related post you can do: '0' + (new Date().getMonth() + 1).toString().slice(-2)
Explanation:
Since '0'
is not a number but a string when you add (+
) with another string then it would be concatenated. Then .slice(-2)
gives us the last two characters of the string. If it's single digit then it would be 0x
month, if it's double digits then it would be 0 + xx
month which are returned.
See snippet for example:
var d = '0' + (new Date().getMonth() + 1).toString().slice(-2) + '-' + new Date().getFullYear().toString();
document.getElementById("demo").innerHTML = d;
<p id="demo"></p>
Alternatively if you don't want a trailing 0 on double digit months (Oct, Nov, Dec) you could do a little checking based on month digit length: (new Date().getMonth() + 1).length > 1 ? new Date().getMonth() + 1 : '0' + (new Date().getMonth() + 1)
var month = (new Date().getMonth() + 1).length > 1 ? new Date().getMonth() + 1 : '0' + (new Date().getMonth() + 1);
var date = (month).toString().slice(-2) + '-' + new Date().getFullYear().toString();
document.getElementById("demo").innerHTML = date;
<p id="demo"></p>
Upvotes: 18
Reputation: 42516
Alternatively, you can import DatePipe
, or FormatDate
into your component.ts.
1) DatePipe:
import { DatePipe } from '@angular/common';
export class SampleComponent implements OnInit {
constructor(private datePipe: DatePipe) {}
transformDate(date) {
return this.datePipe.transform(date, 'MM-yyyy');
}
}
Do not forget to add DatePipe to your providers in your module.
providers: [DatePipe]
2) formatDate:
import { formatDate } from '@angular/common';
export class SampleComponent implements OnInit {
constructor(@Inject(LOCALE_ID) private locale: string) {}
transformDate(date) {
return formatDate(date, 'MM-yyyy', this.locale);
}
}
Upvotes: 5
Reputation: 2369
You can use the built-in date pipe:
{{date | date:'MM-dd'}}
and pass your own format.
Update
Try something like for a JS-only solution:
m = new Date().getMonth().toString() + 1;
y = new Date().getFullYear().toString();
return m + '-' + y;
Upvotes: 5