Many date format conversion

-1

I need function to standardize date format. I have string with date: 2015-12-01T00:00:00+00:00, 12/31/2018 01:00:00 etc.

I try this code:

public static DateTime ToDateTime(this string date)
        {
            return DateTime.ParseExact(date, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
        }

but I have error:

System.FormatException
  HResult=0x80131537
  Message=The string was not recognized as a valid DateTime element.
  Source=mscorlib
  Ślad stosu:
   w System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
   w System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
   w InsuranceService.Common.ExtensionMethods.StringExtensionMethods.ToDateTime(String date) w \\Mac\Home\Desktop\StringExtensionMethods.cs:wiersz 10
   w AutoMapper.Internal.DelegateBasedResolver`2.Resolve(ResolutionResult source)
   w AutoMapper.NullReferenceExceptionSwallowingResolver.Resolve(ResolutionResult source)
   w AutoMapper.PropertyMap.<>c.<ResolveValue>b__44_0(ResolutionResult current, IValueResolver resolver)
   w System.Linq.Enumerable.Aggregate[TSource,TAccumulate](IEnumerable`1 source, TAccumulate seed, Func`3 func)
   w AutoMapper.PropertyMap.ResolveValue(ResolutionContext context)
   w AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, Object mappedObject, PropertyMap propertyMap)

How to fix it?

c#
asked on Stack Overflow Dec 21, 2018 by fmweifnwe9

1 Answer

1

If you have multiple formats and you know the format of all possible formats, you can ParseExact with all of them.

From your example possible formats

string format1 = "yyyy-MM-ddTHH:mm:sszzzz"; //2015-12-01T00:00:00+00:00"
string format2 = "MM/dd/yyyy HH:mm:ss"; //12/31/2018 01:00:00
string format3 = "dd.MM.yyyy HH:mm:ss"; //01.12.2015 00:00:00

possible inputs

string input1 = "2015-12-01T00:00:00+00:00";
string input2 = "12/31/2018 01:00:00";
string input3 = "01.12.2015 00:00:00";

parsing

DateTime result = DateTime.ParseExact(input1, new[] { format1, format2, format3 }, 
                                      System.Globalization.CultureInfo.InvariantCulture, 
                                      System.Globalization.DateTimeStyles.None);

so ParseExact will pick the first valid format and give you a result.

answered on Stack Overflow Dec 21, 2018 by fubo • edited Dec 21, 2018 by fubo

User contributions licensed under CC BY-SA 3.0