万水千山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理论之时间

posted @ 2017-05-18 13:27  forestk  阅读(792)  评论(0编辑  收藏  举报