-4

I'm making a project with NextJs. Right now I'm making a page where the users are creating activities using useState and fetch POST. I think everything is working somewhat properly however I am having issues with the date.

When I try to post I get an error saying: "The JSON value could not be converted to System.DateTime".

I've come to understand that I need to post a date in accordance to ISO.

I have a date that I set with useState in a Textfield from MUI. I would like that date to be converted to ISO. I have tried different solutions but none have worked.

For further clarification this is what (parts of) my code looks like:

import {Textfield} from "@mui/material";

function CreateActivity {

  var today = new Date();
  var dd = String(today.getDate()).padStart(2, "0");
  var mm = String(today.getMonth() + 1).padStart(2, "0");
  var yyyy = today.getFullYear();

  today = yyyy + "-" + mm + "-" + dd;

  const [activityDate, setActivityDate] = useState(today + "T10:30");

  return (
  
  <div className={styles.textBox}>
     <div>Date, time</div>
        <TextField
           variant="standard"
           id="datetime-local"
           type="datetime-local"
           defaultValue={today + "T10:30"}
           InputLabelProps={{
              shrink: true,
           }}
           onChange={(event) => setActivityDate(event.target.value)}
        />
     </div>
  )
}
Oskar
  • 37
  • 5
  • The problem in your code appears to manifest when trying to make a POST request, can you edit your post to include the relevant code as part of your [mcve]? – Drew Reese Oct 17 '22 at 07:06

1 Answers1

0

I managed to solve it.

What I did was put new Date() in the useState:

const [activityDate, setActivityDate] = useState(new Date());

Which I set with:

<div className={styles.textBox}>
            <div>Date, time</div>
            <TextField
              variant="standard"
              id="datetime-local"
              type="datetime-local"
              defaultValue={today + "T10:30"}
              InputLabelProps={{
                shrink: true,
              }}
              onChange={(event) => setActivityDate(event.target.value)}
            />
          </div>

And then made the value into an object like this:

const activityDateObject = new Date(activityDate + "Z");
Oskar
  • 37
  • 5