Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, September 26, 2011

Convert from UTC Time to Local Time with C#

It's that time of the year again. Yes, it's time for my annual blog post. This one is just a blurb about converting from UTC to Local time on Windows. It's not straightforward so you might find this helpful.

public DateTime GetLocalTimeFromUTC(long theUTCTime = 1314163440)
{
 // Using parameter assignment I set theUTCTime to my birthday.
 // Notice: this UTC is in seconds, it's not from Windows

 // if UTC time is from Windows then you don't need this. .NET returns UTC in milliseconds.
 // If your UTC time comes from elsewhere you'll probably need to multiply by 1000 to get milliseconds theUTCTime *= 1000;

 // make a DateTime for the start of the UTC Epoch
 var aEpochStart = new DateTime(1970, 1, 1);

 // calculate a timespan utilizing windows-specific "ticks"
 var aTimeSpan = new TimeSpan(TimeSpan.TicksPerMillisecond * theUTCTime);

 // add the timespan to the start of the Epoch and you get your local time
 var aLocalTime = aEpochStart.Add(aTimeSpan);
 return aLocalTime;
}

Tuesday, September 14, 2010

Using the Tuple in C# and .NET 4

A new feature in C# for .NET 4 is the Tuple type.  A tuple, in C#, is a group of up to eight items of any type.



var aTuple = 
    new Tuple<string, DateTime>("This is a log entry", DateTime.Now);

I have found this to be a good, direct replacement for methods that take "out" parameters as arguments.  The following example shows a method that returns a list of messages and the total number of messages.

Example 1

public int GetMessages( out IList<string> Messages)
{
  Messages = new List<string>{"hello", "goodbye"};
return 2;
}

var aMessages = new List<string>();
var aCount = GetMessages(aMessages);
var aMessage = aMessages[0];

I prefer my code to be as direct as possible.  I can use a tuple to return multiple types and directly assign the results in my calling code.

Example 2
public Tuple<int, IList<string>> GetMessages()
{
  return new Tuple<int, IList<string>>(2, new List<string>{"hello", "goodbye"});}
}

var aMessages = GetMessages();
var aMessage = aMessages.Item2[0];     // Item2 is the second item in the tuple

Example 2 eliminates a degree of indirection that makes code harder to follow.  In Example 1 I have to infer how aMessages was populated by the program.  If I don't have source code for the GetMessages method in Example 1 that inference might take a little while to get.

For me, direct code is nicer because of its simplicity.  I like simple, direct code because it tends to reduce the number of defects in my projects.  The Tuple type helps me simplify my code and I will be using it from now on.