Mystogan
Mystogan

Reputation: 577

Custom DateTime formatting in c#

I have a variable which is printed out using the following string format:

var printThis = String.Format("{0:d}, {0:T}", dateAndTimeVar);

Now I have a problem; I need '{0:T}' to display something like '--.--.--' when I have not set any time to the 'dateAndTimeVar'. This seems not supported using the regular DateTime type (showing '00.00.00' by default if there is no time set).

I can change the 'dateAndTimeVar' variable to anything (including other types), but the string formatting must remain the same.

Is there any solution to this?

Upvotes: 2

Views: 512

Answers (4)

Justin Bannister
Justin Bannister

Reputation: 618

You could simply do this:

var printThis = String.Format("{0:d}, {0:T}", dateAndTimeVar)
                      .Replace("00:00:00", "--.--.--");

Upvotes: 0

Pauli Østerø
Pauli Østerø

Reputation: 6916

You would need to create your own IFormatProvider and pass it into the String.Format method like this

String.Format(new MyFormatProvider(), "{0:d}, {0:T}", dateAndTimeVar);

The FormatProvider would then do a pass-through on all formats except T, where you would have your logic for outputting either the native T format for DateTime or --.--.-- if the Time-part of DateTime is 00:00:00.

Read about IFormatProvider on MSDN here

Upvotes: 5

Tim Schmelter
Tim Schmelter

Reputation: 460028

You could simply check if the DateTime contains a time:

String printThis = dateAndTimeVar.Date == dateAndTimeVar ?  
    String.Format("{0:d}, --.--.--", dateAndTimeVar) : 
    String.Format("{0:d}, {0:T}", dateAndTimeVar);

Upvotes: 0

Iain
Iain

Reputation: 6452

This a list of date time patterns you can use

DateTime.ToString() Patterns | GeekZilla

Cheers

Upvotes: 1

Related Questions