Reputation: 577
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
Reputation: 618
You could simply do this:
var printThis = String.Format("{0:d}, {0:T}", dateAndTimeVar)
.Replace("00:00:00", "--.--.--");
Upvotes: 0
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
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
Reputation: 6452
This a list of date time patterns you can use
DateTime.ToString() Patterns | GeekZilla
Cheers
Upvotes: 1