How to make Date objects in "mm-dd-yyyy" format?

I’m trying to create some Dates which I want to display in “mm-dd-yyyy” format. The documentation (https://docs.julialang.org/en/v1/stdlib/Dates/#Constructors) only seems to give examples where the dates are in “yyyy-mm-dd” format. Here’s what I tried:

using Dates
df = DateFormat("mm-dd-yyyy")
date = Date("01-03-2020", df)

This displays as 2020-01-03, but I want it to display as 01-03-2020 (i.e. January 3rd, 2020). I also want to display dates in mm-dd-yyyy format when they appear in a DataFrame. Is there is a simple way to do this?

Edit: I just learned from here Wikibooks that the following will display the date in “mm-dd-yyyy” format as a String:

Dates.format(date, "mm-dd-yyyy")

But is there a way to just change the format in which Date objects are displayed, without having to create a new String object?

Looks like date printing is hard-coded to that format.

You could define your own type with a new show method:

using Dates
df = DateFormat("mm-dd-yyyy")
date = Date("01-03-2020", df)

struct FormattedDate
    date::Date
    format::DateFormat
end
FormattedDate(d::Date) = FormattedDate(d, DateFormat("mm-dd-yyyy"))

Base.show(io::IO, fd::FormattedDate) = Dates.format(io, fd.date, fd.format)

FormattedDate(date)
1 Like

Thank you! This is very helpful :slightly_smiling_face: