Skip to main content
2 of 3
added 205 characters in body
Edmund
  • 43.3k
  • 3
  • 53
  • 148

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 DateValues 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" DateObjects.

dt = toDateObjectDay@"12 May 2017"

Mathematica graphics

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]

Mathematica graphics

Even if the operation involves a lower granularity.

DatePlus[dt, {1, "Hour"}]

Mathematica graphics

Using DateObjects also allows you to use comparison operators.

stringDates = {"3 June 2014", "12 May 2017", "30 Sep 2017", "1 March 2022"};
dates = toDateObjectDay /@ stringDates

Mathematica graphics

Select[# <= dt &]@dates

Mathematica graphics

Select[Between[{Today, DatePlus[Today, {2, "Decade"}]}]]@dates

Mathematica graphics

###Formatted Strings

DateObjects can be converted back to formatted strings with DateString.

DateString[dt, Riffle[{"Day", "MonthNameShort", "Year"}, " "]]
"12 May 2017"

Hope this helps.

Edmund
  • 43.3k
  • 3
  • 53
  • 148