public static class TimeSpanExtensions {
public static TimeSpan Days(this int value) {
return new TimeSpan(value, 0, 0, 0);}
public static TimeSpan Hours(this int value) {
return new TimeSpan(0, value, 0, 0);}
public static TimeSpan Minutes(this int value) {
return new TimeSpan(0, 0, value, 0);}
public static TimeSpan Seconds(this int value) {
return new TimeSpan(0, 0, 0, value);}
public static TimeSpan Milliseconds(this int value) {
return new TimeSpan(0, 0, 0, 0, value);}
public static DateTime Ago(this TimeSpan value) {
return DateTime.Now - value;}}
然后,一个为DateTime。
public static class DateTimeExtensions {
public static DateTime Ago(this DateTime dateTime, TimeSpan delta) {
return dateTime - delta;}}
现在,你可以像下面这样做:
var date = DateTime.Now;date.Ago(2.Days()); // 2 days agodate.Ago(7.Hours()); // 7 hours agodate.Ago(567.Milliseconds()); // 567 milliseconds ago