I have a system that takes information from an external source and then stores it to be displayed later.
One of the data items is a date. On the source system they have the concept of a fuzzy date i.e. not accurate to a specific day or sometimes not to a month as well. So I get dates in the format:
dd/mm/yyyy mm/yyyy yyyy
I can parse these to DateTime objects and work with these but when rendering later I need to be able to determine the accuracy of the date since parsing "2010" will result in a date of "01/01/2010". I want to show just the year so need to know it's original accuracy.
I've mocked up a quick class to deal with this:
public class FuzzyDate { public DateTime Date { get; set; } public DateType Type { get; set; } } public enum DateType { DayMonthYear, MonthYear, Year }
This will do the job for me and I can do something on the parse to handle it but I feel like this is probably quite a common problem and there is probably an existing cleaner solution.
Is there something built into .Net to do this? I had a look at the culture stuff but that didn't quite seem right.
Any help would be appreciated.
The "fff" custom format specifier represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.
To set dates in C#, use DateTime class. The DateTime value is between 12:00:00 midnight, January 1, 0001 to 11:59:59 P.M., December 31, 9999 A.D.
To answer your question: There is nothing built into .NET to handle this gracefully.
Your solution is as valid as any I've seen. You will probably wish to embellish your class with overrides to the ToString() method that will render your date appropriately based on the DateType.
Here are a couple other threads that attempt to address this question:
Strategy for Incomplete Dates
Implementing a "Partial Date" object
Good luck!
If your data type will always handle specific periods of time (i.e. the year 1972 is a specific period of time, but the 4th of July is not specific), you can store your data as a start time and time span.
Here's a possible implementation:
public struct VagueDate { DateTime start, end; public DateTime Start { get { return start; } } public DateTime End { get { return end; } } public TimeSpan Span { get { return end - start; } } public VagueDate(string Date) { if (DateTime.TryParseExact(Date, "yyyy", null, 0, out start)) end = start.AddYears(1); else if (DateTime.TryParseExact(Date, "MM/yyyy", null, 0, out start)) end = start.AddMonths(1); else if (DateTime.TryParseExact(Date, "dd/MM/yyyy", null, 0, out start)) end = start.AddDays(1); else throw new ArgumentException("Invalid format", "Date"); } public override string ToString() { return Start.ToString("dd/MM/yyyy") + " plus " + Span.TotalDays + " days"; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With