資料庫儲存 datetime.utcnow() 而非 datetime.now(),原因有三:
後端只輸出 ISO 8601 UTC 字串(如 2024-01-15T08:30:00Z),交由瀏覽器依使用者系統時區、語系格式化顯示。優勢:
document.write 限制靜態頁)。# 下載 moment.min.js 至 static/js/
# 或使用 CDN
#
base.html<!doctype html>
<html>
<head>
<script src="{{ url_for('static', filename='js/moment.min.js') }}"></script>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
_moment.html<script>
document.write(moment("{{ utc_iso }}").format('LLL'));
</script>
<noscript>{{ utc_iso }}</noscript>
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)
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 | 日曆風格 |
動態載入內容時 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 同樣適用此架構。