Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
<<<<<<< HEAD
node_modules
=======
scripts/node_modules/
>>>>>>> origin/main
184 changes: 184 additions & 0 deletions docs-templates/api/components/relativetime.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
---
title: RelativeTime
description: API reference for the RelativeTime component
---

## Overview

The `<RelativeTime>` component renders a localized relative time string, such as "2 hours ago" or "in 3 days".
It supports two usage modes: automatically selecting the best unit from a `Date`, or explicitly specifying a value and unit.

```jsx
<RelativeTime>{someDate}</RelativeTime>
// Output: "2 hours ago"
```

All formatting is handled locally using the [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat) API.

## Reference

### Props

<TypeTable
type={{
"children?": {
description: 'A Date object to compute relative time from now.',
type: 'Date',
optional: true,
default: 'undefined',
},
"date?": {
description: 'A Date object to compute relative time from now. Alias for children.',
type: 'Date',
optional: true,
default: 'undefined',
},
"value?": {
description: 'Explicit numeric value for relative time. Requires unit.',
type: 'number',
optional: true,
default: 'undefined',
},
"unit?": {
description: 'The unit of time. Required when using value.',
type: 'Intl.RelativeTimeFormatUnit',
optional: true,
default: 'undefined',
},
"name?": {
type: 'string',
optional: true,
default: 'undefined',
},
"options?": {
type: 'Intl.RelativeTimeFormatOptions',
optional: true,
default: '{}',
},
"locales?": {
type: 'string[]',
optional: true,
default: 'undefined',
},
}}
/>

### Description
| Prop Name | Description |
|-----------|-------------|
| `children` | A `Date` object. The component automatically selects the best unit (seconds, minutes, hours, days, weeks, months, or years) and formats the time relative to now. |
| `date` | Alias for `children`. A `Date` object to compute relative time from now. If both are provided, `date` takes precedence. |
| `value` | An explicit numeric value for the relative time (e.g., `-1` for "yesterday"). Must be used together with `unit`. |
| `unit` | The unit of time (e.g., `'second'`, `'minute'`, `'hour'`, `'day'`, `'week'`, `'month'`, `'year'`). Required when using `value`. |
| `options` | Optional formatting options following the [`Intl.RelativeTimeFormatOptions` specification](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat). Use this to control `numeric` and `style` behavior. |
| `locales` | Optional locales to specify the formatting locale. If not provided, the user's locale is used. Read more about specifying locales [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). |

### Returns

`JSX.Element` containing the formatted relative time as a string, or `null` if no date or value is provided.

---
## Examples

### Auto-select unit from a Date
Pass a `Date` as children and the component automatically picks the best unit.

```jsx title="PostTimestamp.jsx" copy
import { RelativeTime } from '__PACKAGE_NAME__';

export default function PostTimestamp({ post }) {
return (
<RelativeTime>{post.createdAt}</RelativeTime> // [!code highlight]
);
// Output: "2 hours ago", "3 days ago", "in 5 minutes", etc.
}
```

### Using the date prop
You can also pass the date via the `date` prop instead of `children`.

```jsx title="PostTimestamp.jsx" copy
import { RelativeTime } from '__PACKAGE_NAME__';

export default function PostTimestamp({ post }) {
return (
<RelativeTime date={post.createdAt} /> // [!code highlight]
);
}
```

### Explicit value and unit
Specify an exact value and unit, mirroring the `Intl.RelativeTimeFormat` API.

```jsx title="Reminder.jsx" copy
import { RelativeTime } from '__PACKAGE_NAME__';

export default function Reminder() {
return (
<p>
Your trial ends <RelativeTime value={3} unit="day" />. // [!code highlight]
</p>
);
// Output: "Your trial ends in 3 days."
}
```

### Specifying locales
Display relative time in a specific locale.

```jsx title="FrenchTimestamp.jsx" copy
import { RelativeTime } from '__PACKAGE_NAME__';

export default function FrenchTimestamp({ date }) {
return (
<RelativeTime locales={['fr-FR']}>{date}</RelativeTime> // [!code highlight]
);
// Output: "il y a 2 heures"
}
```

### Translating RelativeTime
Wrap `<RelativeTime>` in a `<T>` component to include it in a translated sentence.

```jsx title="Comment.jsx" copy
import { T, RelativeTime } from '__PACKAGE_NAME__';

export default function Comment({ comment }) {
return (
<T id="commentPosted">
Posted <RelativeTime>{comment.createdAt}</RelativeTime> // [!code highlight]
</T>
);
}
```

### Custom formatting options
Control the output style with `Intl.RelativeTimeFormat` options.

```jsx title="VerboseTimestamp.jsx" copy
import { RelativeTime } from '__PACKAGE_NAME__';

export default function VerboseTimestamp({ date }) {
return (
<RelativeTime
options={{
numeric: 'auto', // [!code highlight]
style: 'long', // [!code highlight]
}}
>
{date}
</RelativeTime>
);
// With numeric: 'auto', outputs "yesterday" instead of "1 day ago"
}
```

---

## Notes
* The `<RelativeTime>` component is a variable component that formats relative time values.
* When using auto mode (with a `Date`), the component selects the most appropriate unit automatically.
* The component uses [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat) under the hood.

## Next steps
* For more details and usage examples of the `<RelativeTime>` component and other variable components like `<DateTime>`, `<Currency>`, `<Num>`, and `<Var>`, see the [Using Variable Components](__DOCS_PATH__/guides/variables) documentation.
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
---
title: formatRelativeTimeFromDate
description: API reference for the formatRelativeTimeFromDate method to format relative time from a Date
---

## Overview

The `formatRelativeTimeFromDate` method takes a `Date` and formats it as a localized relative time string, automatically selecting the most appropriate unit.

```typescript
const gt = new GT({ targetLocale: 'en-US' });

const formatted = gt.formatRelativeTimeFromDate(
new Date(Date.now() - 3600000)
);
// Returns: "1 hour ago"
```

## Reference

### Parameters

| Name | Type | Description |
|------|------|-------------|
| `date` | `Date` | The date to format relative to now |
| `options?` | `Intl.RelativeTimeFormatOptions & { locales?: string \| string[] }` | Optional formatting configuration |

### Options

| Name | Type | Description |
|------|------|-------------|
| `locales?` | `string \| string[]` | Override locales for formatting (defaults to instance locales) |
| `numeric?` | `'always' \| 'auto'` | Whether to always use numeric output (default: `'auto'`) |
| `style?` | `'long' \| 'short' \| 'narrow'` | The length of the output |

### Returns

`string` - The formatted relative time string (e.g., "2 hours ago", "in 3 days").

---

## Examples

### Basic usage

```typescript copy
import { GT } from 'generaltranslation';

const gt = new GT({ targetLocale: 'en-US' });

// Recent timestamps
const fiveMinAgo = new Date(Date.now() - 5 * 60 * 1000);
console.log(gt.formatRelativeTimeFromDate(fiveMinAgo));
// Output: "5 minutes ago"

// Future dates
const nextWeek = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
console.log(gt.formatRelativeTimeFromDate(nextWeek));
// Output: "in 1 week"
```

### Different locales

```typescript copy
const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000);

console.log(gt.formatRelativeTimeFromDate(twoHoursAgo, { locales: 'es-ES' }));
// Output: "hace 2 horas"

console.log(gt.formatRelativeTimeFromDate(twoHoursAgo, { locales: 'zh-CN' }));
// Output: "2小时前"
```

### Natural language output

```typescript copy
const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);

console.log(gt.formatRelativeTimeFromDate(yesterday, { numeric: 'auto' }));
// Output: "yesterday"
```

---

## Notes

* Automatically selects the best unit based on the time difference
* Unit selection follows natural thresholds: seconds → minutes → hours → days → weeks → months → years
* Uses `Intl.RelativeTimeFormat` under the hood

## Related methods

* See [`formatRelativeTime`](/docs/core/class/methods/formatting/format-relative-time) for explicit value + unit formatting
* See [`formatDateTime`](/docs/core/class/methods/formatting/format-date-time) for absolute date formatting
* See standalone [`formatRelativeTimeFromDate`](/docs/core/functions/formatting/format-relative-time-from-date) for use without GT instance
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
---
title: formatRelativeTime
description: API reference for the formatRelativeTime method to format relative time strings according to locale conventions
---

## Overview

The `formatRelativeTime` method formats a numeric value and time unit into a localized relative time string.

```typescript
const gt = new GT({ targetLocale: 'en-US' });

const formatted = gt.formatRelativeTime(-1, 'day', {
numeric: 'auto'
});
// Returns: "yesterday"
```

## Reference

### Parameters

| Name | Type | Description |
|------|------|-------------|
| `value` | `number` | The numeric value (negative for past, positive for future) |
| `unit` | `Intl.RelativeTimeFormatUnit` | The unit of time (`'second'`, `'minute'`, `'hour'`, `'day'`, `'week'`, `'month'`, `'year'`) |
| `options?` | `Intl.RelativeTimeFormatOptions & { locales?: string \| string[] }` | Optional formatting configuration |

### Options

| Name | Type | Description |
|------|------|-------------|
| `locales?` | `string \| string[]` | Override locales for formatting (defaults to instance locales) |
| `numeric?` | `'always' \| 'auto'` | Whether to always use numeric output (default: `'auto'`) |
| `style?` | `'long' \| 'short' \| 'narrow'` | The length of the output |

### Returns

`string` - The formatted relative time string.

---

## Examples

### Basic usage

```typescript copy
import { GT } from 'generaltranslation';

const gt = new GT({ targetLocale: 'en-US' });

// Past
console.log(gt.formatRelativeTime(-2, 'hour'));
// Output: "2 hours ago"

// Future
console.log(gt.formatRelativeTime(3, 'day'));
// Output: "in 3 days"

// Natural language
console.log(gt.formatRelativeTime(-1, 'day', { numeric: 'auto' }));
// Output: "yesterday"
```

### Different locales

```typescript copy
console.log(gt.formatRelativeTime(-1, 'week', { locales: 'fr-FR' }));
// Output: "la semaine dernière"

console.log(gt.formatRelativeTime(2, 'month', { locales: 'ja-JP' }));
// Output: "2 か月後"
```

---

## Notes

* Uses browser-native `Intl.RelativeTimeFormat` for formatting
* When `numeric` is `'auto'`, special values like -1 day may produce "yesterday" instead of "1 day ago"

## Related methods

* See [`formatRelativeTimeFromDate`](/docs/core/class/methods/formatting/format-relative-time-from-date) for auto-selecting the unit from a Date
* See [`formatDateTime`](/docs/core/class/methods/formatting/format-date-time) for absolute date formatting
* See standalone [`formatRelativeTime`](/docs/core/functions/formatting/format-relative-time) for use without GT instance
* Check out [`Intl.RelativeTimeFormat` documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat) for more options
2 changes: 1 addition & 1 deletion docs/en-US/core/class/methods/formatting/meta.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"title": "Formatting",
"pages": ["./format-cutoff", "./format-date-time", "./format-list-to-parts", "./format-message", "./format-num"]
"pages": ["./format-cutoff", "./format-date-time", "./format-relative-time", "./format-relative-time-from-date", "./format-list-to-parts", "./format-message", "./format-num"]
}
Loading
Loading