Евгений Евгений - 17 days ago 5
C# Question

Convert DateTime in another format

I have an object, one of its propperty is DateTime DateofBirth. i get this object and want to change


{8/16/1978 12:00:00 AM}


to


{16/8/1978 12:00:00 AM}


.

DateTime? tmp = externalConsumerProfile.DateOfBirth;
string s=DateTime.ParseExact(tmp.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy hh:mm:ss tt") ;


But i have an error when try to convert


An exception of type 'System.FormatException' occurred in mscorlib.dll
but was not handled in user code

Additional information: String was not recognized as a valid DateTime.


When i try
tmp.ToString("dd/MM/yyyy hh:mm:ss tt")
z have an error


No overloads for method ToString

Answer

All you need to do is format your DateTime value. You don't need to parse it.

DateTime? tmp = externalConsumerProfile.DateOfBirth;
string s=tmp.HasValue() ? tmp.Value.ToString("dd/MM/yyyy hh:mm:ss tt") : string.Empty;