«

»

Dec 20

Converting Date to and from UTC in PowerBuilder.NET & .NET Framework




Converting from UTC to Local & Local to UTC using .NET Framework

 

Converting dates from or to UTC in the .NET Framework is pretty simple as the DateTime class has many built in features including many conversion related functions.

 

Notice

When you parse a string into a date you will need to be careful in knowing what time zone the date and time string is from but assuming you know what date time you are working with you simply use the SpecifyKind method of the DateTime class.

 

Example .NET Framework Date Conversion Code ( UTC / Local )

The .NET code for performing the UTC to local and back conversion is listed below.

 

// Get date for current moment adjusted for local time zone.
DateTime utcNow = DateTime.UtcNow;
DateTime localNow = DateTime.Now;

// convert the UTC date to Local
newDate = DateTime.SpecifyKind( utcNow, DateTimeKind.Local );
// convert the Local time to UTC
newDate = DateTime.SpecifyKind( localNow, DateTimeKind.Utc );

 

2 comments

  1. Carolyn

    Your overall success when writing for people as a blogger
    will rely in part upon being able to take ‘old’ news and present it
    in a ‘new’ way. Even if you are only adding a few paragraphs, try to
    update it at least every couple of days.
    Carolyn recently posted..CarolynMy Profile

  2. Mark

    Hi Rich,

    I had to do the same thing for a system. The datetime values are stored in the db as Utc. Several months ago I created a class to handle the conversions on the client. I created two methods called ToUtc and ToLocal. ToUtc checks the incoming datetime’s Kind property and if its not Utc calls ToUniversalTime. ToLocal checks the incoming datetime’s Kind property and if its not Local calls ToLocalTime. I probably could have saved myself some time if I’d noticed the SpecifyKind method for the Datetime class.

    Thanks for sharing,
    Mark

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv badge