Format a DateTime using a Microsoft Word date picker content control format string

3.4k views Asked by At

Microsoft Word's date picker content control (which you can add to a document through the hidden-by-default Developer ribbon) uses date/time formatting strings that are slightly incompatible with DateTime.ToString. For example:

M/d/yyyy h:mm am/pm

If I use the same format in DateTime.ToString:

DateTime.Parse("11/13/2014 12:00 PM").ToString("M/d/yyyy h:mm am/pm")

The result is "11/13/2014 12:00 a0/p0". The expected result is what Word displays, "11/13/2014 12:00 PM" (yes, PM is capitalized).

Is there a safe way to use a date format extracted from a Word content control to format a date in C#?

2

There are 2 answers

2
Soner Gönül On

There is no am or pm as a custom date and time format specifiers.

You need to use "tt" custom format specifier which represents the entire AM/PM designator of your CurrentCulture.

DateTime.Parse("11/13/2014 12:00 PM").ToString("M/d/yyyy h:mm tt")

Your program thinks your a and p characters as a literal string delimiter and m specifier is for minutes. Since your single digit minute of your DateTime is 0, your am / pm will be a0 / p0

And remember, "/" custom format specifier has a special meaning of replace me with current culture or supplied culture date separator. That means if your CurrentCulture's DateSeparator is not /, your result will have your current date separator, not /.

0
Joey Adams On

If you simply want to set a Word date content control's value to a date, respecting its formatting:

DateTime dt = ...;
ContentControl contentControl = ...;

contentControl.Range.Text = ""; // ensure Word reformats date
contentControl.Range.Text = dt.ToString();

Setting the content control text property is like typing a value into the content control as a user. When you type a date into the content control, Word parses and reformats it, or shows the text as given if it couldn't parse it.

The .Text = "" prevents Word from using the formatting given by .ToString() when the date being assigned is the same as the date already in the control. I found that when a date picker content control is mapped to a custom XML value, if I change the date, Word will reformat it, but if I change the formatting of the date (e.g. change "February" to "Feb" or even change "Tuesday" to "Saturday"), Word will preserve my formatting. By clearing the content control text first, Word treats the date assignment as a value change and thus reformats the date.