andrew4582

TimeHelper

Jun 6th, 2012
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.67 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Core {
  4.    
  5.     /// <summary>
  6.     /// All times are in Universal Time
  7.     /// </summary>
  8.     public static class TimeHelper {
  9.        
  10.         /// <summary>
  11.         /// Converts the time to Local Time
  12.         /// </summary>
  13.         public static DateTime FromUnixTimeLocal(long seconds) {
  14.             return FromUnixTime(seconds).ToLocalTime();
  15.         }
  16.  
  17.         /// <summary>
  18.         /// All times are in Universal Time
  19.         /// </summary>
  20.         public static DateTime FromUnixTime(long seconds) {
  21.             var time = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
  22.             time = time.AddSeconds(seconds);
  23.             return time;
  24.         }
  25.        
  26.         /// <summary>
  27.         /// All times are in Universal Time
  28.         /// </summary>
  29.         public static DateTime? FromUnixTimeNull(string secondsString) {
  30.             if(string.IsNullOrWhiteSpace(secondsString))
  31.                 return null;
  32.  
  33.             long seconds = 0L;
  34.  
  35.             if(!long.TryParse(secondsString,out seconds))
  36.                 return null;
  37.  
  38.             return FromUnixTime(seconds);
  39.         }
  40.         /// <summary>
  41.         /// All times are in UTC, if the <see cref="dateTime"/> is a local time is is converted to Universal Time
  42.         /// </summary>
  43.         public static long ToUnixTime(DateTime dateTime) {
  44.  
  45.             if(dateTime.Kind == DateTimeKind.Local)
  46.                 dateTime = dateTime.ToUniversalTime();
  47.            
  48.             var timeSpan = (dateTime - new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc));
  49.             var timestamp = (long)timeSpan.TotalSeconds;
  50.            
  51.             return timestamp;
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment