How to get current month and display in html?


#1

Hello guys,

How can I get current month, next month and display them in h4 tag?
ion-datetime can get current date but it also has a built-in date picker which isn’t necessary in my project.


#2
  • option 1: (new Date()).getMonth() gives you the month as a number, which you can convert to a string by writing your own function
  • option 2: use the format function of the date-fns library

#3

Thanks but how can I get the next month in MMMM format?
I.e, the next month is June… and I want to display it in letters, not numbers.


#4
const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const thisMonth = monthNames[(new Date()).getMonth()];
const nextMonth = monthNames[(new Date()).getMonth() + 1];

#5

Thanks a lot! I will try now.


#6

Some more options:


#7

Until moment.js supports tree-shaking I’d echo @pwespi recommendation of using date-fns.


#8

In addition to the tree-shaking and bloat concerns, moment’s requirement for using a dedicated blackbox object is irritating, whereas date-fns can work directly with either Dates or strings.

OP’s question can also be addressed directly using only date-fns (with i18n free as well):

let now = new Date();
let nowMonth = format(now, "MMMM");
let oneMonthLater = addMonths(now, 1);
let nextMonth = format(oneMonthLater, "MMMM");

#9

Yes, its not perfect but a lot of the bloat comes from locales and you can filter them out.

See: https://medium.com/@kudochien/a-react-webpack-optimization-case-27da392fb3ec