如何在moment.js中将“几秒前”替换为“刚刚”并实现自定义相对时间显示
Customize Moment.js Relative Time to Show "刚刚" for 0-59 Seconds
Got it, let's tweak your React code to make Moment.js display "刚刚" (just now) for any relative time within 0-59 seconds, while keeping the normal format for times longer than a minute. Here's how to make it work:
Key Fix: Use Functions in relativeTime Configuration
Moment.js lets us use functions instead of static strings in the relativeTime locale settings. This gives us the flexibility to conditionally return "刚刚" for second-level relative times, and keep standard formatting for everything else.
Updated Working Code
import "./styles.css"; import { useEffect, useState } from "react"; import moment from "moment"; // Load Chinese locale for proper Chinese relative time formatting import "moment/locale/zh-cn"; export default function App() { // Customize the relative time rules moment.updateLocale("zh-cn", { relativeTime: { future: "in %s", past: "%s前", // Return "刚刚" for any second-range time (0-59 seconds ago) s: () => "刚刚", ss: () => "刚刚", // Keep normal format for minutes and above m: "1分钟", mm: "%d分钟", h: "1小时", hh: "%d小时", d: "1天", dd: "%d天", w: "1周", ww: "%d周", M: "1个月", MM: "%d个月", y: "1年", yy: "%d年" } }); const MINUTE_MS = 60000; // Use state to trigger re-renders when time updates const [currentTime, setCurrentTime] = useState(Date.now()); useEffect(() => { const interval = setInterval(() => { setCurrentTime(Date.now()); }, 1000); // Update every second to see dynamic changes return () => clearInterval(interval); }, []); // Example: Timestamp 5 seconds ago (should show "刚刚") const recentTimestamp = () => currentTime - 5 * 1000; // Example: Timestamp 2 minutes ago (should show "2分钟前") const twoMinutesAgo = () => currentTime - 2 * MINUTE_MS; moment.locale("zh-cn"); return ( <div className="App"> <div>5秒前: {moment(recentTimestamp()).fromNow()}</div> <div>2分钟前: {moment(twoMinutesAgo()).fromNow()}</div> </div> ); }
What Changed & Why?
- Chinese Locale Setup: I switched to the
zh-cnlocale (and imported it) to ensure proper Chinese relative time formatting. If you need to stick with the English locale but show Chinese text, just swapzh-cnwithenand adjust the string values (like changingpast: "%s ago"topast: "%s前"). - Second-Level Time Handling: Replaced static strings for
s(single second) andss(multiple seconds) with functions that always return "刚刚". This covers every case where the relative time falls within 0-59 seconds. - Dynamic Updates: Added
currentTimestate to refresh the component every second, so you can see the relative time behavior change in real-time. - Clear Examples: Included two timestamp examples to demonstrate both cases—"刚刚" for recent seconds, and standard formatted time for longer durations.
内容的提问来源于stack exchange,提问作者Khan Naxim
相关产品推荐
相关产品推荐

