Skip to main content

formatDate

Reference

formatDate function is used to format the given dateTime string into given dateFormat & time format as the local time of any specified time zone.

const { protrakUtils, protrakComponents } 
= React.useContext(customWidgetContext);

const { formatDate } = protrakUtils;

const formattedDate = formatDate(
"2023-05-03T00:00:00.000Z",
"dd/MMM/yy",
"(UTC-09:00) Alaska",
"HH:MM:SS"
);

Parameters

  • formatDate function has 4 parameters:
    • dateString : date value in string format
    • dateFormat : specify the dateFormat e.g. dd/MM/yyyy
    • userTimeZone : timezone to which date need to be converted
    • timeFormat : optional parameter with default value ''.
  • Developer can refer Date Format section in Tenant Settings in admin configuration for values of dateFormat, timeFormat, userTimeZone.

Returns

  • formatDate function returns a formatted date string e.g. '03/May/23 15:00:00'

Caveats

  1. Requires Valid Inputs:

    • dateString must be a valid date; invalid inputs return an empty string.
  2. Time Zone Dependency:

    • A valid userTimeZone is required for accurate formatting. Missing or incorrect time zones can lead to errors.
  3. Format Compatibility:

    • dateFormat and timeFormat must follow date-fns formatting rules. Incorrect formats may cause errors.
  4. No Input Validation:

    • The function does not validate inputs, so invalid dateString or formats may produce unexpected results.
  5. Performance:

    • Frequent calls with large datasets may impact performance due to repeated parsing and formatting.
  6. Edge Cases:

    • Handling of daylight saving time (DST) or ambiguous time zones may lead to inaccuracies.

Usage

function TenantInfoWidget(pageContext) {
const { protrakUtils, protrakComponents }
= React.useContext(customWidgetContext);

const { formatDate} = protrakUtils;
const {Grid, H2, H3, Text} = protrakComponents;

const { name: tenantName, dateTimeFormat: tenantDateTimeFormat }
= pageContext.settings;

const formattedDate = formatDate(
new Date(),
tenantDateTimeFormat.dateFormat,
tenantDateTimeFormat.timeZone,
tenantDateTimeFormat.timeFormat );

return (
<Grid
display="grid"
height="auto"
rows={['auto']}
columns={['auto']}
areas={[['top']]}
alignItems="center"
padding={'1.5em 1.5em'}
margin={'4px'}
border={'1px solid #818181'}
>
<H2>Tenant Info</H2>
<Text>
<H3> Tenant Name: </H3>
{tenantName}
</Text>
<H3> DateTime Format: </H3>
<ul>
<li><b>Date Format: </b> {tenantDateTimeFormat.dateFormat} </li>
<li><b>Time Format: </b> {tenantDateTimeFormat.timeFormat}</li>
<li><b>TimeZone: </b> {tenantDateTimeFormat.timeZone}</li>
</ul>
<Text>
<H3> Current date time: </H3> {formattedDate}
</Text>
</Grid>
);
}

Here's a preview of how this custom widget looks like.

formatDate

Troubleshooting

  • check if valid arguments are passed to formatDate function