i'm looking way differentiate time spans, example, between 8am-9am , 8pm-9pm, 10am-12pm , 10pm-12am, etc. in .net.
since time relative, i'm looking creative way on how achieve this.
here's i've tried far:
// 3:41pm - 4:41pm datestart: 5/7/2015 3:41:41 pm dateexpire: 5/7/2015 4:41:41 pm dateexpire.subtract(datestart): 01:00:00 tounixepoctime(datestart): 1431013301 tounixepoctime(dateexpire): 1431016901 int timespan = tounixepoctime(dateexpire) - tounixepoctime(datestart); timespan: 3600 // 4:41pm - 5:41pm datestart: 5/7/2015 4:41:41 pm dateexpire: 5/7/2015 5:41:41 pm dateexpire.subtract(datestart): 01:00:00 tounixepoctime(datestart): 1431016901 tounixepoctime(dateexpire): 1431020501 int timespan = tounixepoctime(dateexpire) - tounixepoctime(datestart); timespan: 3600
... i'm not sure why these results surprised me make sense - it's basic subtraction.
as stated, timespan time interval. time intervals 8am-9am , 8pm-9pm same - 1 hour. if want differentiate them, create own class hold start , end time of each interval , use these values compare objects:
public class daterange { public daterange(datetime start, datetime end) { if (end < start) throw new argumentexception("end"); start = start; end = end; } public datetime start { get; private set; } public datetime end { get; private set; } public timespan duration { { return end - start; }} public override bool equals(object obj) { daterange other = obj daterange; if (other == null) return false; return start == other.start && end == other.end; } // override gethashcode }
now if have 2 date ranges
var morningrange = new daterange(8amtime, 9amtime); var eveningrange = new daterange(8pmtime, 9pmtime);
they not same, duration same
morningrange.duration == eveningrange.duration // true morningrange.equals(eveningrange) // false
you can define ==
, !=
operators
public static bool operator== (daterange x, daterange y) { if (object.referenceequals(x, y)) return true; if (((object)x == null) || ((object)y == null)) return false; return x.equals(y); } public static bool operator !=(daterange x, daterange y) { return !(x == y); }
now comparison more easy
morningrange == eveningrange // false morningrange != eveningrange // true
Comments
Post a Comment