萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Flask 日期時間最佳實踐:UTC 儲存 + Moment.js 前端渲染

為什麼要統一用 UTC?

資料庫儲存 datetime.utcnow() 而非 datetime.now(),原因有三:

  1. 遷移無痛:伺服器遷移時區無需更新既有資料。
  2. 全球一致:不同時區用戶看到的「絕對時間點」相同。
  3. 排序正確:UTC 時間字串按字典序即為時間序。

前端轉換才是正解

後端只輸出 ISO 8601 UTC 字串(如 2024-01-15T08:30:00Z),交由瀏覽器依使用者系統時區、語系格式化顯示。優勢:

  • 自動適應夏令時間、12/24 小時制、年月日順序等本地化細節。
  • 減輕後端負擔,API 保持純粹。
  • AJAX 動態載入內容同樣適用(document.write 限制靜態頁)。

整合 Moment.js 步驟

1. 安裝

# 下載 moment.min.js 至 static/js/
# 或使用 CDN
# 

2. 基礎模板 base.html

<!doctype html>
<html>
<head>
    <script src="{{ url_for('static', filename='js/moment.min.js') }}"></script>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

3. 顯示 UTC 時間的通用片段 _moment.html

<script>
document.write(moment("{{ utc_iso }}").format('LLL'));
</script>
<noscript>{{ utc_iso }}</noscript>

4. 視圖函數傳遞 UTC ISO 字串

from datetime import datetime
from flask import render_template

@app.route('/post/')
def post(id):
    post = Post.query.get_or_404(id)
    # 假設 post.timestamp 為 UTC datetime 物件
    utc_iso = post.timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')
    return render_template('post.html', post=post, utc_iso=utc_iso)

5. 文章模板 post.html

{% extends "base.html" %}
{% block content %}
<article>
    <h1>{{ post.title }}</h1>
    <time>{% include '_moment.html' %}</time>
    <div>{{ post.body }}</div>
</article>
{% endblock %}

進階格式化選項

格式字串輸出範例適用場景
'LLLL'Monday, January 15, 2024 4:30 PM完整日期時間
'LL'January 15, 2024僅日期
'LT'4:30 PM僅時間
'fromNow()'2 hours ago相對時間(動態需 JS 定時更新)
'calendar()'Today at 4:30 PM日曆風格

AJAX 情境下的替代方案

動態載入內容時 document.write 失效,改用:

<span class="moment" data-utc="{{ utc_iso }}"></span>

<script>
document.querySelectorAll('.moment').forEach(el => {
    el.textContent = moment(el.dataset.utc).format('LLL');
});
</script>

結語

後端只管 UTC,前端管顯示——這是現代 Web 應用處理時間的黃金法則。Moment.js 雖已進入維護模式,但 date-fns、Luxon、原生 Intl.DateTimeFormat 同樣適用此架構。

copyright © 萬盛學電腦網 all rights reserved