Formatting a date like the Calendar component does

UI Components for React
Post Reply
Master_T
Posts: 14
Joined: 13 Dec 2021, 11:57

16 Dec 2021, 18:48

Hi

I'm using the Calendar component to allow users to edit a date, and I set the format with the dateFormat attribute, like this:

Code: Select all

<Calendar dateFormat="dd/mm/yy" value={date} onChange={(e) => setDate(e.value)}></Calendar>
In another area of the application, I would like to display the same date using the same format string used in the dateFormat attribute.
So my question is: is there a way to access the Calendar component's date formatting utility, in order to format a date from code?
Or, alternatively, is there a date formatting library that uses the same format strings that are used in the dateFormat attribute, so I can replicate the same behavior?

mcandu
Posts: 107
Joined: 20 Jan 2021, 16:31

17 Dec 2021, 10:07

Hi,

You can use ref prop with useRef() to reach calendar props. See this example: https://codesandbox.io/s/nifty-water-9k33x

Master_T
Posts: 14
Joined: 13 Dec 2021, 11:57

17 Dec 2021, 12:08

mcandu wrote:
17 Dec 2021, 10:07
Hi,

You can use ref prop with useRef() to reach calendar props. See this example: https://codesandbox.io/s/nifty-water-9k33x
Hello mcandu, thanks for your reply. However, maybe you misunderstood my question: I'm not interested in recovering the dateFormat string from a Calendar instance, I have that string already, it's a user setting in my app. What I want to do is format a Date object in another part of my app using the same format "engine", so to speak, that the Calendar component uses. In other words, I assume the Calendar component internally calls a "formatDate()" method of some kind that takes the dateFormat string and the Date object as input and outputs the formatted date. What I'm looking for is that method, if it is accessible in some way, or at least a copy of the algorithm it uses if not.

Master_T
Posts: 14
Joined: 13 Dec 2021, 11:57

21 Dec 2021, 13:30

Well, I solved it like this:

I created a ref to a Calendar instance:

Code: Select all

private dummyCal = React.createRef<Calendar>();
then I hooked it up to a dummy invisible Calendar:

Code: Select all

<Calendar ref={this.dummyCal} style={{display: 'none'}} dateFormat={this.myDateFormat} />
now, I can format the date by using:

Code: Select all

dummyCal.current['formatDate'](date);

Post Reply

Return to “PrimeReact”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 5 guests