Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace Core {
- /// <summary>
- /// All times are in Universal Time
- /// </summary>
- public static class TimeHelper {
- /// <summary>
- /// Converts the time to Local Time
- /// </summary>
- public static DateTime FromUnixTimeLocal(long seconds) {
- return FromUnixTime(seconds).ToLocalTime();
- }
- /// <summary>
- /// All times are in Universal Time
- /// </summary>
- public static DateTime FromUnixTime(long seconds) {
- var time = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
- time = time.AddSeconds(seconds);
- return time;
- }
- /// <summary>
- /// All times are in Universal Time
- /// </summary>
- public static DateTime? FromUnixTimeNull(string secondsString) {
- if(string.IsNullOrWhiteSpace(secondsString))
- return null;
- long seconds = 0L;
- if(!long.TryParse(secondsString,out seconds))
- return null;
- return FromUnixTime(seconds);
- }
- /// <summary>
- /// All times are in UTC, if the <see cref="dateTime"/> is a local time is is converted to Universal Time
- /// </summary>
- public static long ToUnixTime(DateTime dateTime) {
- if(dateTime.Kind == DateTimeKind.Local)
- dateTime = dateTime.ToUniversalTime();
- var timeSpan = (dateTime - new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc));
- var timestamp = (long)timeSpan.TotalSeconds;
- return timestamp;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment