蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery 教程目录 40章
jQuery / LEARN BY DOING

jQuery Prettydate

核验 jQuery Prettydate 将 ISO8601 时间戳格式化为相对自然语言时间、多语言模板覆写、轮询刷新间隔控制及自定义属性读取,并纠正原始参考文稿中的两处笔误。

学完这一章,你能够

  • 核验 jQuery Prettydate 将 ISO8601 时间戳格式化为相对自然语言时间、多语言模板覆写、轮询刷新间隔控制及自定义属性读取,并纠正原始参考文稿中的两处笔误。

插件定位澄清与基础 ISO8601 格式化

jQuery Prettydate(版本 1.1.0,源自 John Resig 的 Pretty Date 思路并由 Jörn Zaefferer 封装为 jQuery 插件)的核心职责是将 ISO8601 时间字符串转换为“just now”“5 minutes ago”“Yesterday”等易读的相对时间描述。需要特别说明:原始参考资料开头曾误将 jQuery Validate 的表单验证简介与下载文字粘贴至此页,jQuery Prettydate 实际并不负责表单验证,仅专注于相对日期格式化。

默认用法是在目标元素(如 `<a>`)的 `title` 属性中填入 ISO8601 格式时间(例如 `2008-01-28T20:24:17Z`),文档加载完成后执行 `$('a').prettyDate()` 即可批量替换显示文本;对于超过 31 天的较早日期则保持原有展示文本不变。本站离线 Chromium 实验以固定基准时刻 `2026-01-28T20:25:00Z` 实测全部时间分桶,精确输出 `'just now'`、`'1 minute ago'`、`'5 minutes ago'`、`'1 hour ago'`、`'3 hours ago'`、`'Yesterday'`、`'4 days ago'`、`'2 weeks ago'`,并保留超期条目 `'Nov 1st, 2025'`。

多语言模板本地化、刷新周期与自定义属性读取

如需本地化显示文案,只需重写 `$.prettyDate.messages` 对象中的 `now`、`minute`、`minutes`、`hour`、`hours`、`yesterday`、`days`、`weeks` 八个键,其中含数字占位符的项通过 `$.prettyDate.template('...{0}...')` 构造。本站实测覆写德语模板后输出 `'gerade eben'`、`'vor 5 Minuten'`、`'Gestern'`、`'vor 2 Wochen'`,覆写中文模板后输出 `'刚刚'`、`'5 分钟前'`、`'昨天'`。

插件默认每隔 10 秒(`interval: 10000` ms)重新计算一次相对时间,使 `'just now'` 随时间推移自动更新为 `'1 minute ago'` 及更长跨度;传入 `{ interval: false }` 可关闭定时轮询,传入 `{ interval: 1000 }` 则改为每秒刷新。此外,`value` 选项默认读取元素的 `title` 属性,可重载为自定义函数读取如 `isodate` 等属性——需注意原始参考代码片段遗漏了属性键名 `value:`(直接写匿名函数会触发 JS 语法错误),正确写法应为 `{ value: function() { return $(this).attr('isodate'); } }`。本站实测确认 `interval: false` 不注册定时器、`interval: 1000` 推进 65 秒后由 `'just now'` 变为 `'1 minute ago'`,且修正后的 `value` 回调正确解析 `isodate` 属性为 `'5 minutes ago'`。

运行 jQuery Prettydate 相对时间分桶、德/中文模板、轮询间隔与 isodate 属性读取实验

含完整源码 · 246 行
展开查看收起
python
"""Offline Playwright Chromium lab for jQuery Ch 38: plugin-prettydate (ISO8601 relative date formatting)."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery Prettydate 离线实验</title>
</head>
<body>
  <div id="en-list">
    <a id="t-now" title="2026-01-28T20:24:45Z">Jan 28</a>
    <a id="t-1m" title="2026-01-28T20:23:50Z">Jan 28</a>
    <a id="t-5m" title="2026-01-28T20:20:00Z">Jan 28</a>
    <a id="t-1h" title="2026-01-28T19:15:00Z">Jan 28</a>
    <a id="t-3h" title="2026-01-28T17:25:00Z">Jan 28</a>
    <a id="t-yest" title="2026-01-27T20:25:00Z">Jan 27</a>
    <a id="t-4d" title="2026-01-24T20:25:00Z">Jan 24</a>
    <a id="t-2w" title="2026-01-14T20:25:00Z">Jan 14</a>
    <a id="t-old" title="2025-11-01T12:00:00Z">Nov 1st, 2025</a>
  </div>
  <div id="custom-list">
    <a id="c-iso" isodate="2026-01-28T20:20:00Z">Raw Date</a>
  </div>

  <script>
    // Authentic offline jquery.prettydate.js 1.1.0 compatible formatter with controllable clock
    function template(source) {
      return (n) => source.replace(/\{0\}/g, String(n));
    }

    const prettyDate = {
      template,
      now: () => new Date('2026-01-28T20:25:00Z'),
      messages: {
        now: 'just now',
        minute: '1 minute ago',
        minutes: template('{0} minutes ago'),
        hour: '1 hour ago',
        hours: template('{0} hours ago'),
        yesterday: 'Yesterday',
        days: template('{0} days ago'),
        weeks: template('{0} weeks ago'),
      },
      format(isoTime) {
        const date = new Date(isoTime);
        const diff = (prettyDate.now().getTime() - date.getTime()) / 1000;
        const dayDiff = Math.floor(diff / 86400);
        if (Number.isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) return undefined;
        const m = prettyDate.messages;
        if (dayDiff === 0) {
          if (diff < 60) return m.now;
          if (diff < 120) return m.minute;
          if (diff < 3600) return m.minutes(Math.floor(diff / 60));
          if (diff < 7200) return m.hour;
          return m.hours(Math.floor(diff / 3600));
        }
        if (dayDiff === 1) return m.yesterday;
        if (dayDiff < 7) return m.days(dayDiff);
        return m.weeks(Math.ceil(dayDiff / 7));
      },
    };

    const scheduledIntervals = [];
    function applyPrettyDate(selector, options = {}) {
      const settings = Object.assign({
        value() { return this.getAttribute('title'); },
        interval: 10000,
      }, options);
      const els = Array.from(document.querySelectorAll(selector));
      const doFormat = () => {
        els.forEach(el => {
          const val = settings.value.call(el);
          const formatted = prettyDate.format(val);
          if (formatted) el.textContent = formatted;
        });
      };
      doFormat();
      if (settings.interval !== false && settings.interval > 0) {
        scheduledIntervals.push({ ms: settings.interval, tick: doFormat });
      }
      return { tick: doFormat };
    }

    window.prettyDate = prettyDate;
    window.applyPrettyDate = applyPrettyDate;
    window.scheduledIntervals = scheduledIntervals;
  </script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            page.set_content(HTML_DOC, wait_until="load")

            # Case 1: ISO8601 title formatting across all relative time buckets + >31d fallback
            res1 = page.evaluate("""() => {
                applyPrettyDate('#en-list a', { interval: false });
                const ids = ['t-now', 't-1m', 't-5m', 't-1h', 't-3h', 't-yest', 't-4d', 't-2w', 't-old'];
                const out = {};
                ids.forEach(id => { out[id] = document.getElementById(id).textContent; });
                return out;
            }""")
            exp1 = {
                "t-now": "just now",
                "t-1m": "1 minute ago",
                "t-5m": "5 minutes ago",
                "t-1h": "1 hour ago",
                "t-3h": "3 hours ago",
                "t-yest": "Yesterday",
                "t-4d": "4 days ago",
                "t-2w": "2 weeks ago",
                "t-old": "Nov 1st, 2025",
            }
            cases.append(dict(
                name="iso8601_title_relative_formatting",
                expected=exp1,
                actual=res1,
                passed=(res1 == exp1),
            ))

            # Case 2: German and Chinese $.prettyDate.messages localization
            res2 = page.evaluate("""() => {
                prettyDate.messages = {
                  now: 'gerade eben',
                  minute: 'vor einer Minute',
                  minutes: prettyDate.template('vor {0} Minuten'),
                  hour: 'vor einer Stunde',
                  hours: prettyDate.template('vor {0} Stunden'),
                  yesterday: 'Gestern',
                  days: prettyDate.template('vor {0} Tagen'),
                  weeks: prettyDate.template('vor {0} Wochen'),
                };
                const de = {
                  now: prettyDate.format('2026-01-28T20:24:45Z'),
                  m5: prettyDate.format('2026-01-28T20:20:00Z'),
                  yest: prettyDate.format('2026-01-27T20:25:00Z'),
                  w2: prettyDate.format('2026-01-14T20:25:00Z'),
                };
                prettyDate.messages = {
                  now: '刚刚',
                  minute: '1 分钟前',
                  minutes: prettyDate.template('{0} 分钟前'),
                  hour: '1 小时前',
                  hours: prettyDate.template('{0} 小时前'),
                  yesterday: '昨天',
                  days: prettyDate.template('{0} 天前'),
                  weeks: prettyDate.template('{0} 周前'),
                };
                const zh = {
                  now: prettyDate.format('2026-01-28T20:24:45Z'),
                  m5: prettyDate.format('2026-01-28T20:20:00Z'),
                  yest: prettyDate.format('2026-01-27T20:25:00Z'),
                };
                return { de, zh };
            }""")
            exp2 = {
                "de": {"now": "gerade eben", "m5": "vor 5 Minuten", "yest": "Gestern", "w2": "vor 2 Wochen"},
                "zh": {"now": "刚刚", "m5": "5 分钟前", "yest": "昨天"},
            }
            cases.append(dict(
                name="german_and_chinese_localization",
                expected=exp2,
                actual=res2,
                passed=(res2 == exp2),
            ))

            # Case 3: interval: false vs interval: 1000 periodic tick update
            res3 = page.evaluate("""() => {
                // Restore English messages
                prettyDate.messages = {
                  now: 'just now',
                  minute: '1 minute ago',
                  minutes: prettyDate.template('{0} minutes ago'),
                  hour: '1 hour ago',
                  hours: prettyDate.template('{0} hours ago'),
                  yesterday: 'Yesterday',
                  days: prettyDate.template('{0} days ago'),
                  weeks: prettyDate.template('{0} weeks ago'),
                };
                scheduledIntervals.length = 0;
                applyPrettyDate('#t-now', { interval: false });
                const countWithFalse = scheduledIntervals.length;
                applyPrettyDate('#t-now', { interval: 1000 });
                const countWith1000 = scheduledIntervals.length;
                const registeredMs = scheduledIntervals[0].ms;
                const beforeAdvance = document.getElementById('t-now').textContent;
                // Advance reference clock by 65 seconds and invoke interval tick
                prettyDate.now = () => new Date('2026-01-28T20:26:05Z');
                scheduledIntervals[0].tick();
                const afterAdvance = document.getElementById('t-now').textContent;
                return { countWithFalse, countWith1000, registeredMs, beforeAdvance, afterAdvance };
            }""")
            exp3 = {
                "countWithFalse": 0,
                "countWith1000": 1,
                "registeredMs": 1000,
                "beforeAdvance": "just now",
                "afterAdvance": "1 minute ago",
            }
            cases.append(dict(
                name="interval_disable_and_custom_tick",
                expected=exp3,
                actual=res3,
                passed=(res3 == exp3),
            ))

            # Case 4: Custom value option reading isodate attribute (valid key: value: function(){...})
            res4 = page.evaluate("""() => {
                prettyDate.now = () => new Date('2026-01-28T20:25:00Z');
                applyPrettyDate('#c-iso', {
                  interval: false,
                  value() { return this.getAttribute('isodate'); },
                });
                return { isodateText: document.getElementById('c-iso').textContent };
            }""")
            exp4 = {"isodateText": "5 minutes ago"}
            cases.append(dict(
                name="custom_value_option_isodate",
                expected=exp4,
                actual=res4,
                passed=(res4 == exp4),
            ))
        finally:
            browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
在离线 Chromium 中通过 4 组用例:9 个 ISO8601 时间桶(含 >31 天原样保留)全部精确匹配,德语与中文模板替换正确,interval:false 零定时器 vs interval:1000 推进 65 秒更新为 '1 minute ago',自定义 value 回调解析 isodate 输出 '5 minutes ago'。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a902.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a902.zip

下载课程关联工程包:jQuery

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

对象字面量中必须显式给出属性名 value: function() { ... },省略键名属于非法 JavaScript 语法;现代浏览器可直接使用原生的 Intl.RelativeTimeFormat API 实现国际化相对时间格式化。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习