ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

TimesSelector

Inspired from ye good old ruby on rails, provides you with new DateTime instances based on an integer you provide. Look at realfiction.net -> extension methods for more detail

Source

public abstract class TimeSelector {
protected TimeSpan myTimeSpan;

internal int ReferenceValue {
  set { myTimeSpan = MyTimeSpan(value); }
}

public DateTime Ago { get { return DateTime.Now - myTimeSpan; } }
public DateTime FromNow { get { return DateTime.Now + myTimeSpan; } }
public DateTime AgoSince(DateTime dt) { return dt - myTimeSpan; }
public DateTime From(DateTime dt) { return dt + myTimeSpan; }
protected abstract TimeSpan MyTimeSpan(int refValue);

  }

  public class WeekSelector : TimeSelector {
protected override TimeSpan MyTimeSpan(int refValue) { return new TimeSpan(7 * refValue, 0, 0, 0); }
  }

  public class DaysSelector : TimeSelector {
protected override TimeSpan MyTimeSpan(int refValue) { return new TimeSpan(refValue, 0, 0, 0); }
  }

  public class YearsSelector : TimeSelector {
protected override TimeSpan MyTimeSpan(int refValue) {
  return new TimeSpan(365 * refValue, 0, 0, 0);
}
  }

public static class Extensions {
    
    public static WeekSelector Weeks(this int value) {
        var ws = new WeekSelector();
        ws.ReferenceValue = value;
        return ws;
    }

    public static YearsSelector Years(this int value) {
        var ws = new YearsSelector();
        ws.ReferenceValue = value;
        return ws;
    }

    public static DaysSelector Days(this int value) {
        var ws = new DaysSelector();
        ws.ReferenceValue = value;
        return ws;
    }

}

Example

Console.WriteLine(3.Weeks().Ago);
Console.WriteLine(5.Years().FromNow);
Console.WriteLine(19.Days().From(new DateTime(2007,1,1)));

Author: Frank Quednau

Submitted on: 5 mrt. 2008

Language: C#

Type: System.Int32

Views: 4915