You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Moment.js实现UI本地化日期自定义字符串输出?

Solution Using Moment.js

To achieve this localized date formatting, we can create a custom function that leverages Moment.js's locale data and date comparison features. Here's a straightforward implementation tailored to your requirements:

Step 1: Set Up Moment.js with Locales

First, make sure you have Moment.js installed and include the necessary locale files (like fr.js for French support).

For npm Projects

Install Moment.js via npm:

npm install moment

Then import Moment and your desired locale:

import moment from 'moment';
import 'moment/locale/fr'; // Import French locale (add others as needed)

For Browser Usage

Include the scripts directly in your HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/locale/fr.min.js"></script>

Set the active locale to switch between languages:

moment.locale('fr'); // Use 'en' for English, 'fr' for French, etc.

Step 2: Custom Formatting Function

This function checks how far the target date is from today and returns the appropriate localized string:

function formatLocalizedDate(date) {
    const targetDate = moment(date);
    const today = moment().startOf('day');
    const daysDifference = targetDate.diff(today, 'days');
    const localeData = moment.localeData();
    // Get locale-specific short date format (MM/DD/YYYY for English, DD/MM/YYYY for French)
    const dateFormat = localeData.longDateFormat('L');

    // Handle Today
    if (daysDifference === 0) {
        const todayLabel = localeData.calendar('sameDay').replace(/^\[(.*)\]$/, '$1');
        return `${todayLabel}, ${targetDate.format(dateFormat)}`;
    }

    // Handle Tomorrow
    if (daysDifference === 1) {
        const tomorrowLabel = localeData.calendar('nextDay').replace(/^\[(.*)\]$/, '$1');
        return `${tomorrowLabel}, ${targetDate.format(dateFormat)}`;
    }

    // Handle Dates Within Next 7 Days (2-6 days from today)
    if (daysDifference >= 2 && daysDifference <= 6) {
        return `${targetDate.format('dddd')}, ${targetDate.format(dateFormat)}`;
    }

    // Handle Dates Beyond 7 Days
    if (daysDifference >= 7) {
        const futurePrefix = localeData.relativeTimeFuture(); // "in %s" (en) or "dans %s" (fr)
        const daysString = localeData.relativeTime(daysDifference, false, 'd', false); // "10 days" or "10 jours"
        const inXDays = futurePrefix.replace('%s', daysString);
        return `${inXDays}, ${targetDate.format(dateFormat)}`;
    }

    // Fallback for past dates (adjust as needed)
    return targetDate.format(dateFormat);
}

Step 3: Test the Function

Let's verify with your examples to ensure it works as expected:

English Locale (moment.locale('en'))

console.log(formatLocalizedDate('2018-02-06')); // "Today, 02/06/2018"
console.log(formatLocalizedDate('2018-02-07')); // "Tomorrow, 02/07/2018"
console.log(formatLocalizedDate('2018-02-12')); // "Monday, 02/12/2018"
console.log(formatLocalizedDate('2018-02-16')); // "In 10 days, 02/16/2018"

French Locale (moment.locale('fr'))

console.log(formatLocalizedDate('2018-02-06')); // "Aujourd’hui, 06/02/2018"
console.log(formatLocalizedDate('2018-02-07')); // "Demain, 07/02/2018"
console.log(formatLocalizedDate('2018-02-12')); // "Lundi, 12/02/2018"
console.log(formatLocalizedDate('2018-02-16')); // "dans 10 jours, 16/02/2018"

Key Details

  • Locale Adaptability: The function uses Moment's built-in localized strings, so it automatically adjusts to any supported language without manual string updates.
  • Date Format Consistency: The L token ensures the date follows the locale's standard short format (e.g., DD/MM/YYYY for French, MM/DD/YYYY for English).
  • Edge Case Handling: The fallback for past dates can be modified if you need to handle historical dates differently.

内容的提问来源于stack exchange,提问作者Luckylooke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:05:04