Django:具有基于 class 的视图和清晰形式的本地时间表示
Django: Local time representation with class-based views and crispy forms
我正在使用 Django 构建一个拍卖网站。不同时区的用户可能会使用它,因此我决定所有基础日期和时间(例如模型中的日期时间值)都将采用 UTC。
我正在使用基于 class 的视图(ListView、DetailView 等)并且显示清晰。
在页面上转换为当地时间的最佳策略是什么?我应该在视图中还是在模板中进行?
谢谢@Ejaz。我决定反对 Moment.js,但这给了我一个正确方向的推动 - 我没有想过用 Javascript 来做。我在基本模板中添加了一个函数,然后从单独的模板中调用它
{# base.html #}
<script>
function utc2local_dt(utcDateTime) {
const options = { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', hour12: false };
var localDateTime = new Date(utcDateTime).toLocaleDateString('en-GB', options);
return localDateTime;
}
</script>
{# myTemplate.html #}
<td><a id="local-dt-auction-end" class="" href="#"></a></td>
.
.
<script>
document.getElementById("local-dt-auction-end").text = utc2local_dt('{{ listing.datetime_auction_end|date:"c" }}');
</script>
{% endblock content %}
我正在使用 Django 构建一个拍卖网站。不同时区的用户可能会使用它,因此我决定所有基础日期和时间(例如模型中的日期时间值)都将采用 UTC。
我正在使用基于 class 的视图(ListView、DetailView 等)并且显示清晰。
在页面上转换为当地时间的最佳策略是什么?我应该在视图中还是在模板中进行?
谢谢@Ejaz。我决定反对 Moment.js,但这给了我一个正确方向的推动 - 我没有想过用 Javascript 来做。我在基本模板中添加了一个函数,然后从单独的模板中调用它
{# base.html #}
<script>
function utc2local_dt(utcDateTime) {
const options = { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', hour12: false };
var localDateTime = new Date(utcDateTime).toLocaleDateString('en-GB', options);
return localDateTime;
}
</script>
{# myTemplate.html #}
<td><a id="local-dt-auction-end" class="" href="#"></a></td>
.
.
<script>
document.getElementById("local-dt-auction-end").text = utc2local_dt('{{ listing.datetime_auction_end|date:"c" }}');
</script>
{% endblock content %}