万水千山ABP - 时区问题

 

关于时间和时区问题,后面的参考文章中有详细的描述。

我遇到的问题是:

在MVC视图页面中,显示记录的生成时间 CreationTime

<div>
@Model.CreationTime
</div>

我使用的是 UTC 时间,页面显示的结果也确实是正确的UTC时间,然而,但是,这不是我们所期望的本地时间。

万水千山之后,找到了 ABP 提供的帮助类 Abp.Timing.Timezone.TimezoneHelper。

直接贴时区转换代码:

@using Abp.Timing.Timezone;
<div>
@TimezoneHelper.ConvertFromUtc(Model.CreationTime, TimeZoneInfo.Local.Id)
</div>

TimeZoneInfo.Local.Id  返回表示本地时区的 TimeZoneInfo 对象的Id。System.TimeZoneInfo 类是 .net 类,和 abp 无关。

TimezoneHelper.ConvertFromUtc 方法将UTC时间转为指定时区Id的当地时间。

 

到这里,你或许发现,好傻,把简单问题搞复杂了。一点不错,还不就是个时区转换问题吗,关 ABP P 事。难怪ABP的文档都不提怎么在页面中直接显示本地时间。

好吧,其实,看 ABP 的源码,TimezoneHelper.ConvertFromUtc 方法就一句代码:

public static DateTime? ConvertFromUtc(DateTime? date, string toTimeZoneId)
{
return Convert(date, "UTC", toTimeZoneId);
}

简单一点,我的代码就该是

<div>
@Convert(Model.CreationTime, "UTC", TimeZoneInfo.Local.Id)
</div>

简单是简单了,却多了一个 "UTC",而且,而且,无关ABP了 ......

 

另外,在 JS 脚本中,可使用 moment.js 实现,如显示 ABP 使用的实例代码

moment(data.record.creationTime).format('YYYY-MM-DD HH:mm:ss')

 

再好好学习之后,我们发现,ABP是支持多时区的。查看 Abp\Timing\Timezone\TimeZoneConverter.cs 源码文件,发现它提供了几个时间转换函数.

下面列出它实现的接口的定义:

namespace Abp.Timing.Timezone
{
    //
    // 摘要:
    //     Interface for timezone converter
    public interface ITimeZoneConverter
    {
        //
        // 摘要:
        //     Converts given date to application's time zone. If timezone setting is not specified,
        //     returns given date.
        //
        // 参数:
        //   date:
        //     Base date to convert
        DateTime? Convert(DateTime? date);
        //
        // 摘要:
        //     Converts given date to tenant's time zone. If timezone setting is not specified,
        //     returns given date.
        //
        // 参数:
        //   date:
        //     Base date to convert
        //
        //   tenantId:
        //     TenantId to convert date for
        DateTime? Convert(DateTime? date, int tenantId);
        //
        // 摘要:
        //     Converts given date to user's time zone. If timezone setting is not specified,
        //     returns given date.
        //
        // 参数:
        //   date:
        //     Base date to convert
        //
        //   tenantId:
        //     TenantId of user
        //
        //   userId:
        //     UserId to convert date for
        DateTime? Convert(DateTime? date, int? tenantId, long userId);
    }
}

特此补充,以免误导。后面有时间再补充......

 

参考:

ABP Timing

ABP理论之时间

转载于:https://www.cnblogs.com/forestk/p/6872872.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值