How to format dates on frontend

Viewed 320

I am using the React (recharts) integration of cube and was wondering how to format dates or "weeks" instead of having the full ISOdate.

For example Week 39 instead of 2021-09-27T00:00:00.000 on the charts and views.

I tried looking at the docs but can't find it. Thanks!

2 Answers

You can reformat your date data before passing it to the chart, use moment.js to get the week number Documentation

moment(date).week();

make sure to set the locale region because the week starts on Monday or Sunday depends on the region:

//this is for France
import 'moment/locale/fr'
moment.locale('fr')

(EDIT) : You can use other libraries for this purpose such as Day.js or date-fns.

I wouldn't recommend using moment.js since it has been deprecated try using date-fns ,it offers more customization Here is the snippet of using date-fns.

    import { format } from "date-fns";
    
    const getWeek = new Date('2021-09-27T00:00:00.000')
    const result = format(getWeek,"Io")) //here "Io" stands for ISO week of year,
   //result -> 39th 

In fact you can modify as per your conveniant, how to display the week here is the document of that date-fns format
just in case you want the visual I have added a codesandbox week format using date-fns

Related