Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Converting DateTime Properties to UTC - .NET Framework

RSS
Modified on Thu, Jun 08, 2017, 11:13 AM by Administrator Categorized as ·Net Framework

Overview

When working with DateTime fields in a Web API implementation, we frequently store them in the database in UTC. However, time zone information is lost when serving the data to a front end caller. We would like to be able to specify the time zone (that is, UTC) for the DateTime fields. This article shows how.

Fundamentals

When working with a DateTime object, it is simple enough to "tack on" the time zone info by using the SpecifyKind static method. This method creates a new DateTime object in the time zone specified and _without changing the time of day_.

DateTime dt = new DateTime(2017, 1, 1, 10, 0, 0);
// dt = 01/01/2017 10:00:00 in unspecified time zone

var dt2 = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
// dt2 = 01/01/2017 10:00:00 UTC

Code Generator

When working with a DTO (data transfer object), it would be convenient if the DateTime and DateTime? properties would implement the above strategy in their set accessor code. That way, any code that uses it wouldn't have to. The following T-SQL script will generate such code.

SQL Script

declare
     @PropertyName  varchar(100)    = 'LastEditedOn'
    ,@Nullable      bit             = 1

declare 
     @PrivateVariable   varchar(101) = '_' + lower(substring(@PropertyName, 1, 1)) + substring(@PropertyName, 2, 99)
    ,@DataType          varchar(30) = 'DateTime' + case when @Nullable = 1 then '?' else '' end

select
     Seq    = 100
    ,Code   = 'private ' + @DataType + ' ' + @PrivateVariable + ';'
union select 110, 'public ' + @DataType + ' ' + @PropertyName
union select 120, '{'
union select 130, '    get { return ' + @PrivateVariable + '; }'
union select 140, '    set { ' + @PrivateVariable + ' = ' 
                    + case when @Nullable = 1 then 'value == null ? (DateTime?)null : ' + 'DateTime' + '.SpecifyKind(value.Value, DateTimeKind.Utc)'
                        else 'DateTime.SpecifyKind(value, DateTimeKind.Utc)'
                        end 
                    + '; }'
union select 150, '}'

Sample Output

private DateTime? _lastEditedOn;
public DateTime? LastEditedOn
{
    get { return _lastEditedOn; }
    set { _lastEditedOn = value == null ? (DateTime?)null : DateTime.SpecifyKind(value.Value, DateTimeKind.Utc); }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.