Home > Net >  extract date from string that contains time as well in C#
extract date from string that contains time as well in C#

Time:06-28

I get an string from one of DTO i.e. "2020-05-17T00:00:00" and this is automapped to one of view model. Actually i only need date part i.e. 2020-05-17 and not time part from it.

Within automapper i tried directly formatting string in following way.

String.Format("{0:yyyy-MM-dd}",)

but automapper says that this can only be done within a type and not during mapping.

Also tried below way but still failed to format string.

   .ForMember(src => src.FromDate, act => act.MapFrom(dest => DateTime.ParseExact(dest.FromDate, "yyyy-MM-dd", CultureInfo.InvariantCulture)))

Not able to track where the issue is.

Any pointers or help is welcomed.

CodePudding user response:

Try to get a DateTime instead of string then use the method

.ToShortDateString()

If you can't get a DateTime, convert the string to DateTime with

DateTime oDate = DateTime.Parse(iDate);

Then use the toshortdatestring

  • Related