Search code examples
c#jquerydatetimewebapiisodate

Passing and dealing with UK date formats from Jquery to C# Web API


I've been developing an site and everything seemed to be going fine. I was sending my dates by converting them to ISO format as it's the only thing my C# WebAPI would accept (that I can work out). However I found that now we're in June and try for example to send 10/06/2021. The date sent would now have a day subtracted from them.

I've tried all sorts of different things. But they either turn out as invalid data or just in American format?

What I have tried:

var closeDate = convertDateTo($("#tbShiftDate").val());

which goes to:

function convertDateTo(dateStr) {
    var parts = dateStr.replace("/", "-").replace("/", "-");
    parts = parts.split("-")
    return new Date(parts[2], parts[1] - 1, parts[0])
}

Which returns Fri Jun 11 2021 00:00:00 GMT+0100 (British Summer Time)

But then

closeDate.toISOString()

Changes this to 2021-06-10T23:00:00.000Z

I found this

closeDate = new Date($("#tbShiftDate").val()).toJSON();

But that ends up sending it in US format 2021-11-06T00:00:00.000Z

Is there a way I can send the date like 2021-06-11T00:00:00.000Z? Or do I have to send them to my controller as a string and then convert them into a DateTime there? Or is there another way I'm missing?

Any help would be great, thanks!


Solution

  • Just use string handling

    const convertDateToISO = dateStr => {
      const [dd, mm, yyyy] = dateStr.split("/")
      return `${yyyy}-${mm.padStart(2,"0")}-${dd.padStart(2,"0")}T00:00:00.000Z`;
    }
    
    console.log(convertDateToISO("13/6/2021"))

    If you must use date, I normally normalise on 15:00 to not go over midnight and to not be bothered by winter/summertime

    const convertDateToISO = dateStr => {
      const [dd, mm, yyyy] = dateStr.split("/")
      return new Date(yyyy, mm - 1, dd, 15, 0, 0, 0) // normalise
        .toISOString()
        .split("T")[0]+"T00:00:00.000Z";
    }
    
    console.log(convertDateToISO("13/6/2021"))

    However you might run into these issues:

    How to pass a datetime parameter?