Saturday, June 6, 2009

DateTime operation in .NET Application

DateTime is a very important datatype and data in terms of realtime application. Some of the application that run timely manner and some of the application that generate data (log file) with time.
To generate such report you need to required store information about date and time.

In .NET there is datatype called DateTime. This contain all information about datetime but sometime problem with this too.

For example:

DateTime dt = DateTime.Now;  // 6/6/2009 09:35:00 PM.
This is used to get current current time of system. If you store this time in file or in a database and later you retrieve then you get that time. So at last “6/6/2009 09:35:00 PM” this is going to  store in a file.

Problem occur when you retrieve this later to display information and by some reason you make changes to current time zone of system or sometime timezone of application. So then also you get “6/6/2009 09:35:00 PM.” as data , which is not right.

So best way to store date is UTC format.

DateTime dt = DateTime.UtcNow and after retrieval convert it to LocalTime but for that also you have to confirm that stored DateTime is in Utc format.

DateTime structure contains  methods called ToBinary() and FromBinary().

long binaryDate  = DateTime.Now.ToBinary() ;

Now store ‘binaryDate’ value in database or text file. So later when you get this value.

DateTime dt =  DateTime.FromBinary(binaryDate).  This will generate correct Date and Time even after timezone changed. This is because of binaryDate( Long ) value contain information about TimeZone too. So it automatically adjust as per system timezone.

Apart from this DateTime structure contain one field called ‘Kind’. which contain current DateTime format kind and that is Utc , Local or Unspecified. Many of case when you store simple way DateTime and later you retrieve kind is unspecified. But when you store binary date and later you retrieve you get either Utc or Local.

Please give your comment or any new idea about storing datetime.

No comments: