Created
September 26, 2014 14:50
-
-
Save jamie94bc/ceac7fa8c0062345a6d5 to your computer and use it in GitHub Desktop.
A workaround for a bug in Mono for DateTime.Now for people who also use MvvmCross.
This file contains 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
public static class DateTimeEx { | |
private static IDateTimeProvider _provider; | |
public static DateTime Now { | |
get { | |
if (_provider == null && !Mvx.TryResolve(out _provider)) { | |
return DateTime.Now; | |
} | |
return _provider.Now; | |
} | |
} | |
public static DateTime Today { | |
get { return Now.Date; } | |
} | |
public static DateTime ToUniversalTimeEx(this DateTime dt) { | |
if (dt.Kind == DateTimeKind.Utc) { | |
return dt; | |
} | |
return dt.Add(DateTime.UtcNow - Now); | |
} | |
} | |
public interface IDateTimeProvider { | |
DateTime Now { get; } | |
} |
This file contains 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
public sealed class DroidDateTimeProvider : IDateTimeProvider { | |
public DateTime Now { | |
get { | |
var c = Calendar.Instance; | |
return new DateTime( | |
c.Get(CalendarField.Year), | |
c.Get(CalendarField.Month) + 1, | |
c.Get(CalendarField.DayOfMonth), | |
c.Get(CalendarField.HourOfDay), | |
c.Get(CalendarField.Minute), | |
c.Get(CalendarField.Second), | |
c.Get(CalendarField.Millisecond), | |
DateTimeKind.Local | |
); | |
} | |
} | |
} |
This file contains 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
public sealed class iOSDateTimeProvider : IDateTimeProvider { | |
public DateTime Now { | |
get { return NSDate.Now; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment