Saving time as UTC with NHibernate

In many applications that have world wide users, there is a need to dealing with UTC. In these applications, time is stored in UTC and then showed backed in local time to users. A good solution is not to bother developers to convert time to universal or local time every time manipulating time related data. Instead we could add a bit of code to setter getter of DateTime fields. Unfortunately this solution does not work in NHibernate and possibly other ORMs. Consider following code:

DateTime _myDate;

public virtual DateTime MyDate
    set { _myDate = value;}
    get {return _myDate;}

In this code we can not add a ToLocalTime() or ToUniversalTime() to setter or getter. Because both NHibernate and the application use this same getter and setter. Real solution is to use a helper field. This way the helper field will not persist on database but real field persists on database. Real field mus not be accessible to developer because of confusion and possible unwanted changes. Consider final solution:

public virtual DateTime MyDate //helper field
    set { MyDateUtc = value.ToUniversalTime(); }
    get { return MyDateUtc.ToLocalTime(); }

private DateTime MyDateUtc { set; get; } //real field

All codes are based on Castle Active Record.

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *