npm install --save date-fns react-date-fns-hooks
import * as React from "react";
import * as ReactDOM from "react-dom";
import {FormatRelative} from "react-date-fns-hooks";
ReactDOM.render(
<FormatRelative date={new Date()}/>,
document.getElementById("app")
);
While the <FormatRelative>
components cannot be used without react-dom, the
hooks useFormatRelative
, useFormatDistance
, useFormatDistanceStrict
and
useDateFunction
can also be used in React Native.
import * as React from "react";
import * as ReactDOM from "react-dom";
import {useFormatRelative} from "react-date-fns-hooks";
function Demo({date}: { date: Date }) {
const time = useFormatRelative(date, {
weekStartsOn: 6
});
return <time>{time}</time>
}
ReactDOM.render(
<Demo date={new Date()}/>,
document.getElementById("app")
);
import * as React from "react";
import * as ReactDOM from "react-dom";
import {useFormatRelative} from "react-date-fns-hooks";
import nb from "date-fns/locale/nb";
function Demo({date}: { date: Date }) {
const time = useFormatRelative(date, {
weekStartsOn: 6
});
return <time>{time}</time>
}
ReactDOM.render(
<DateFnsProvider locale={nb}>
<Demo date={new Date()}/>
</DateFnsProvider>,
document.getElementById("app")
);
import * as React from "react";
import {ReactElement} from "react";
import ReactDOM from "react-dom";
import {act} from "react-dom/test-utils";
async function render(component: ReactElement) {
const container = document.createElement("div");
await act(async () => {
ReactDOM.render(component, container);
});
return container;
}
it("formats relative time", async () => {
const baseDate = new Date(2021, 1, 1, 0, 0, 0);
const date = new Date(2021, 6, 1, 0, 0, 0);
const container = await render(
<DateFnsProvider baseDate={baseDate}>
<Demo date={date}/>
</DateFnsProvider>
);
expect(container.innerText).toEqual("6 months ago");
});
To release, update the version number in package.json and run npm run clean && npm run build && npm publish