# Converter to change gregorian date to jalali on view layer of discourse

**URL:** <https://meta.discourse.org/t/converter-to-change-gregorian-date-to-jalali-on-view-layer-of-discourse/61671>\
**Category:** Development\
**Created:** [2017年四月26日 19:43 UTC](https://meta.discourse.org/t/converter-to-change-gregorian-date-to-jalali-on-view-layer-of-discourse/61671 "2017-04-26T19:43:54Z")\
**Posts on this page:** 1\
**Showing post:** 12

<div class="post-metadata">

**Author:** ![Arta\_S](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/arta_s/32/537495_2.png) [@Arta\_S](https://meta.discourse.org/u/Arta_S)\
**Post date:** [2026年一月1日 17:56 UTC](https://meta.discourse.org/t/converter-to-change-gregorian-date-to-jalali-on-view-layer-of-discourse/61671/12 "2026-01-01T17:56:53Z")

</div>

您好，

这实际上是一个简单的过程。

* * *

## 步骤：在 Discourse 前端启用 Shamsi 日期

### 1) 创建主题组件

1. 前往 **Admin → Customize → Themes**
2. 点击 **Components**
3. 点击 **Add → Create new**
4. 命名为：**Shamsi Date Converter (或者您想要的任何名称)**

* * *

### 2) 添加脚本（头部部分）

在组件内部：

1. 打开 **Common → Head**
2. 粘贴 **以下所有内容**
3. 保存

**代码：**

```plaintext
<script>
(function () {
  // 仅在网站语言为波斯语时应用
  if (!document.documentElement.lang.startsWith("fa")) return;

  const formatter = new Intl.DateTimeFormat(
    "fa-IR-u-ca-persian",
    { dateStyle: "medium" }
  );

  function toDate(value) {
    if (!value) return null;

    // epoch (秒或毫秒)
    if (/^\d{10,13}$/.test(value)) {
      const n = Number(value);
      return new Date(value.length === 10 ? n * 1000 : n);
    }

    const d = new Date(value);
    return isNaN(d) ? null : d;
  }

  function process(el) {
    if (el.dataset.shamsi === "1") return;

    const date =
      toDate(el.getAttribute("datetime")) ||
      toDate(el.dataset.time) ||
      toDate(el.getAttribute("title"));

    if (!date) return;

    el.textContent = formatter.format(date);
    el.dataset.shamsi = "1";
  }

  function run(root = document) {
    root.querySelectorAll("time, .relative-date").forEach(process);
  }

  // 初始加载
  run();

  // 处理无限滚动/实时更新
  new MutationObserver(muts => {
    muts.forEach(m => m.addedNodes.forEach(n => {
      if (n.nodeType === 1) run(n);
    }));
  }).observe(document.documentElement, { childList: true, subtree: true });
})();
</script>
___

```

或者，您可以上传我导出的文件并将其分配给您的主题。

[discourse-shamsi-date.zip](https://meta.discourse.org/uploads/short-url/6LUcPq7eJyT4zwRsBkRNT4LCZUY.zip) (1.1 KB)

* * *

## 工作原理

Discourse 已经向您的浏览器发送正常的公历日期；此脚本不会更改数据，它仅通过浏览器本身将日期文本的显示方式转换为 Shamsi（Jalali）。

## 脚本的作用（高层级）

1. 查找那些 `time` 元素
2. 从 `datetime` 读取真实的公历日期
3. 转换为 Shamsi
4. **仅替换可见文本**
5. 每当加载新帖子时重复此操作

就这样。仅此而已。

* * *

这将使您看到如下日期：

 ![image](https://global.discourse-cdn.com/meta/original/4X/2/9/5/2955eae729a397690c9d5a3b423106adb4a60070.jpeg)

您可以在我们的实例上在线查看：[https://forums.7ho.st](https://forums.7ho.st)

祝您好运

---

_[View the full topic](https://meta.discourse.org/t/converter-to-change-gregorian-date-to-jalali-on-view-layer-of-discourse/61671)._
