If you are performing date calculations/comparisons it would be better to work with DateObject
than to work with string representations of dates. With strings you miss out on the many built-in features for handling dates; see Date Operations and Tests on Dates in the Date and Time.
###Convert to DateObject
To explicitly convert a date string you would use DateObject
's string syntax, extract the DateValue
s and then feed that back into DateObject
for a "Day"
granularity date. It is a bit verbose to be explicit so create a pure function with this steps.
toDateObjectDay =
DateObject[
DateValue[DateObject[{#, {"Day", "MonthName", "Year"}}], {"Year", "Month", "Day"}],
"Day"] &;
String dates of this form can be converted to "Day"
DateObject
s.
dt = toDateObjectDay@"12 May 2017"
Notice that this date has "Day"
granularity and no time components since they were note chosen with DateValue
.
###Date Operations & Comparisons
All date operations will preserve the date granularity.
DatePlus[dt, 2]
Even if the operation involves a lower granularity.
DatePlus[dt, {1, "Hour"}]
Using DateObject
s also allows you to use comparison operators.
stringDates = {"3 June 2014", "12 May 2017", "30 Sep 2017", "1 March 2022"};
dates = toDateObjectDay /@ stringDates
Select[# <= dt &]@dates
Select[Between[{Today, DatePlus[Today, {2, "Decade"}]}]]@dates
###Formatted Strings
DateObject
s can be converted back to formatted strings with DateString
.
DateString[dt, Riffle[{"Day", "MonthNameShort", "Year"}, " "]]
"12 May 2017"
Hope this helps.