Last active
January 23, 2017 07:16
-
-
Save wgross/52e2f159a08707a272e4 to your computer and use it in GitHub Desktop.
Some useful extensions of System.DateTime
This file contains hidden or 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
namespace System | |
{ | |
public static class DateTimeExtensions | |
{ | |
public static string ToIso8601String(this DateTime thisDateTime) | |
{ | |
return thisDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffK"); | |
} | |
public static string ToIso8601String(this DateTimeOffset thisDateTime) | |
{ | |
return thisDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffK"); | |
} | |
public static DateTime Replace(this DateTime thisTime, int? year = null, int? month=null, int? day = null, int? hour = null, int? minute = null, int? second=null, int? millisecond=null) | |
{ | |
return new DateTime( | |
year.GetValueOrDefault(thisTime.Year), | |
month.GetValueOrDefault(thisTime.Month), | |
day.GetValueOrDefault(thisTime.Day), | |
hour.GetValueOrDefault(thisTime.Hour), | |
minute.GetValueOrDefault(thisTime.Minute), | |
second.GetValueOrDefault(thisTime.Second), | |
millisecond.GetValueOrDefault(thisTime.Millisecond) | |
); | |
} | |
public static DateTimeOffset Replace(this DateTimeOffset thisTime, int? year = null, int? month = null, int? day = null, int? hour = null, int? minute = null, int? second = null, int? millisecond = null, TimeSpan? offset = null) | |
{ | |
return new DateTimeOffset( | |
year.GetValueOrDefault(thisTime.Year), | |
month.GetValueOrDefault(thisTime.Month), | |
day.GetValueOrDefault(thisTime.Day), | |
hour.GetValueOrDefault(thisTime.Hour), | |
minute.GetValueOrDefault(thisTime.Minute), | |
second.GetValueOrDefault(thisTime.Second), | |
millisecond.GetValueOrDefault(thisTime.Millisecond), | |
offset.GetValueOrDefault(thisTime.Offset) | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment