Created
August 8, 2012 14:22
-
-
Save andresmoschini/3295419 to your computer and use it in GitHub Desktop.
Ejemplos del uso de DateTimeOffset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class DateTimeOffsetExample | |
{ | |
static void Main(string[] args) | |
{ | |
DateTimeOffset localDateTime = DateTimeOffset.Now; // Setting up a DateTimeOffset with my local machine time: 2012-08-07 05:50:00 pm Offset -05:00 (We are in DST) | |
Console.WriteLine(localDateTime.DateTime); // Is a DateTime, the output is the time as was recorded in the client machine (no offset involved): 2012-08-07 05:50:00 pm | |
Console.WriteLine(localDateTime.Offset); // A TimeSpan (hh:mm): -05:00:00 | |
Console.WriteLine(localDateTime.LocalDateTime); // A DateTime, because I'm on the same machine it is: 2012-08-07 05:50:00 pm | |
//I'm creating this particular DateTime Offset for demostration, lets imagine I got this from the DB (for the record the client machine was on Bs As) | |
DateTimeOffset buenosAiresDateTime = DateTimeOffset.Now.ToOffset(new TimeSpan(-3, 0, 0)); | |
Console.WriteLine(buenosAiresDateTime.DateTime); // Output: 2012-08-07 07:50:00 pm | |
Console.WriteLine(buenosAiresDateTime.Offset); // Output: -03:00:00 | |
Console.WriteLine(buenosAiresDateTime.LocalDateTime); // Output: 2012-08-07 05:50:00 pm | |
//Doing it by hand. We don't need to do this on .NET but this code will be similar in other platforms | |
DateTime myDBTime = buenosAiresDateTime.DateTime; // I have Bs As datetime here on a simple DateTime object. | |
TimeSpan offset = new TimeSpan(-3, 0, 0); // I also have the offset of that time. (-3:00) | |
TimeSpan myLocalOffset = new TimeSpan(-5, 0, 0); // My local offset. (-5:00) | |
DateTime UtcTime = myDBTime.Add(-offset); // First Step getting UTC, we just need to remove the offset to get it. (please notice the minus) | |
DateTime myLocalTime = UtcTime.Add(myLocalOffset); // Adding my client computer offset to UTC so I get my local DateTime. | |
Console.WriteLine(myDBTime); // Output: 2012-08-07 07:50:00 pm | |
Console.WriteLine(UtcTime); // Output: 2012-08-07 10:50:00 pm | |
Console.WriteLine(myLocalTime); // Output: 2012-08-07 05:50:00 pm | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Código extraido del mail explicativo de @jfazzini