2

I searched SO to find the answer to this issue, and found "How to add literal strings in a DateTime format?".

I tried the accepted solution, but did not get the result that I expected. My code is below:

DateTime.Now.ToString("'Previously exported on' d 'at' t") which returns "Previously exported on 7 at P"

I had expected it to return "Previously exported on 02/07/2014 at 05:46 PM"

I also tried:

DateTime.Now.ToString("'Previously exported on' f") which returns "Previously exported on 0"

However, if I only use the simple format strings, I get the expected results:

DateTime.Now.ToString("d") returns "02/07/2014"
DateTime.Now.ToString("t") returns "05:46 PM"
DateTime.Now.ToString("f") returns "Friday, February 07, 2014 05:46 PM"

What am I missing? Can the "short" format string NOT be used with the literals?

Community
  • 1
  • 1
Welton v3.60
  • 2,150
  • 6
  • 27
  • 43
  • You got what you asked for. Today is the 7th and for some reason you only like one letter of the am/pm indicator. You didn't say what you *really* wanted so this is right now just as a guessing game. – Hans Passant Feb 07 '14 at 23:06

1 Answers1

2

You can always use the string.Format for this, which allows you to specify the format at each index using { index[,alignment][ :formatString] }. Ie,

string.Format("Previously exported on {0:d} at {0:t}", DateTime.Now);

It looks like the overloaded DateTime.ToString(string format) expects either standard or custom DateTime format string -- it can't accommodate both.

The format parameter should contain either a single format specifier character (see Standard Date and Time Format Strings) or a custom format pattern (see Custom Date and Time Format Strings) that defines the format of the returned string

McGarnagle
  • 96,448
  • 30
  • 213
  • 255