I have a string in the following format yyyyMMdd
and I am trying to get it to look like this:
yyyy-MM-dd
When I try:
Here is an extension method I use.
///
/// Converts a string to a dateTime with the given format and kind.
///
/// The date time string.
/// The date time format.
/// Kind of the date time.
///
public static DateTime ToDateTime(this string dateTimeString, string dateTimeFormat, DateTimeKind dateTimeKind)
{
if (string.IsNullOrEmpty(dateTimeString))
{
return DateTime.MinValue;
}
DateTime dateTime;
try
{
dateTime = DateTime.SpecifyKind(DateTime.ParseExact(dateTimeString, dateTimeFormat, CultureInfo.InvariantCulture), dateTimeKind);
}
catch (FormatException)
{
dateTime = DateTime.MinValue;
}
return dateTime;
}