Home > Enterprise >  ASP.net Core 6 - How to convert serialized dates into DateTime?
ASP.net Core 6 - How to convert serialized dates into DateTime?

Time:04-14

In my controller I have a httpget that requires the input of two dates (ideally without time, but should work either way).

 // GET: api/Shippingschedules/shipname
        [HttpGet("{startdate},{enddate}")]
        public async Task<ActionResult<Shippingschedule>> GetShippingSchedulesByDates(string startdate, string enddate)
        {
            CultureInfo ukCulture = new CultureInfo("en-GB");
            DateTime sDate = DateTime.Parse(startdate, ukCulture.DateTimeFormat);
            DateTime eDate = DateTime.Parse(enddate, ukCulture.DateTimeFormat);

            ActionResult<Shippingschedule> Shippingschedule = await _context.Shippingschedules.Where(
                x => x.StartDate >= sDate && x.EndDate <= eDate).FirstOrDefaultAsync();

            if (Shippingschedule == null)
            {
                return NotFound();
            }

            return Shippingschedule;
        }

When I debug into the sDate line, the program stops with error:

String '1/1/2022' was not recognized as a valid DateTime. at System.DateTime.Parse(String s, IFormatProvider provider)

How do I deserialise this into a real datetime object?

Thanks

CodePudding user response:

try this

using System.Net;

 var startdateDecoded= WebUtility.UrlDecode(startdate);
var enddateDecoded= WebUtility.UrlDecode(enddate);

CultureInfo ukCulture = new CultureInfo("en-GB");
 DateTime sDate = DateTime.Parse(startdateDecoded, ukCulture.DateTimeFormat);

.....

  • Related