Nicole Phillips Nicole Phillips - 1 month ago 15
C# Question

Format a date time string from YYYY/MM/DD to MM/DD/YYYY with no time

I need to take a time that is a string saved like this: "2016-12-26" and convert it to "12/26/2016" so from yyyy-mm-dd to mm/dd/yyyy I am doing so below however I am getting the time too and I need just the date.

Code I'm using:

var parseBooking = DateTime.ParseExact(bookingStartDate.Replace("-", string.Empty), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);

Answer

Conver bookingStartDate to a DateTime object, then use String.Format on the datetime:

DateTime dt = DateTime.ParseExact(bookingStartDate , "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
var parseBooking = String.Format("{0:MM/dd/yyyy}", dt)

If not create a DateTime object from your string and then do the above.

Comments