Is it possible to convert a date that has been set using useState into an ISOString format?

I am currently working on a project using NextJs. One of the issues I am facing involves creating activities for users on a page using useState and fetch POST. Although most things seem to be functioning correctly, I am experiencing difficulties with handling dates.

Whenever I attempt to post, an error message pops up saying: "The JSON value could not be converted to System.DateTime". This indicates that I need to format the date in ISO standard.

The challenge lies in converting a date set using useState in a Textfield from MUI into ISO format. Despite trying various solutions, none have yielded successful results.

To provide more context, below are snippets of my code:

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>
  )
}

Answer №1

I was able to figure it out.

My solution involved initializing useState with new Date():

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

I used it like this:

<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>

After that, I converted the value into an object like so:

const activityDateObject = new Date(activityDate + "Z");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a JSON object in JavaScript using an array

Can anyone assist me with the following code snippet for formatting the current month? var monthNames = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set&apos ...

Guide to Embedding StencilJS components in a Storybook React Application

I am currently in the process of integrating Stencil and Storybook within the same project. While following this setup guide and this one, I encountered a step that requires publishing the component library to NPM, which is not my desired approach. In my ...

Retrieve no data from Firebase using Cloud Functions

I am a beginner with Google Firebase and Cloud Functions, and I recently attempted a basic "hello world" program: Established a connection to Cloud Firestore [beta], which contains over 100,000 records. Retrieved the top record from the database. Below ...

Include a character in a tube using Angular

Hey everyone, I have a pipe that currently returns each word with the first letter uppercase and the rest lowercase. It also removes any non-English characters from the value. I'm trying to figure out how to add the ':' character so it will ...

Tips for updating the value within a textfield in HTML

I am looking to dynamically update the value displayed in my Revenue textfield by subtracting the Cost of Goods from the Sales Price. I have included an image of the current layout for reference, but I want the Revenue field to reflect the updated value af ...

Tips on how to toggle the class of one specific element without affecting others

Whenever I click on a div, it expands. However, if I click on a collapsed one, both collapse and the first one returns to an inactive state. At this point, the last two are in both active and inactive states. And if at this time I click on the first one, t ...

What is the best way to display a resolved promise object in string format on a button, as an example?

I've searched through many similar questions, but none of them seem to address my specific issue in a simple way. Currently, the behavior of my promise is shown in the image below: https://i.sstatic.net/9GETz.png When looking at lines 62 and 63 in ...

Incorporating Content-Disposition headers to enable the file to be both downloaded and opened

I'm having trouble allowing users to both view and download files on a web page. I've tried setting headers and using JavaScript, but can't seem to get it right. My goal is to have an HTML page with two links for each file - one to open in ...

Retrieve an array of specific column values from an array of objects using Typescript

How can I extract an array from an array of objects? Data var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, ...

Top method for extracting mesh vertices in three.js

Being new to Three.js, I may not be approaching this in the most optimal way, I start by creating geometry like this: const geometry = new THREE.PlaneBufferGeometry(10,0); Next, I apply a rotation: geometry.applyMatrix( new THREE.Matrix4().makeRotation ...

"Enhance your website with interactive jQuery lightbox buttons for easy navigation

As I explore the jquery lightbox plugin, I find it to be quite straightforward. However, I am curious if there is a way to make the "previous" and "next" buttons of the plugin function without the images needing to be named sequentially (e.g., "image1.jpg, ...

Achieving a consistent scroll value using RxJs

I have a block with a mat-table inside, which has an initial scroll value of 0. I am trying to achieve a scenario where the scroll value changes automatically to 2 or more when you reach a height of 0 and again changes back to 2 when scrolled to the final ...

Record the success or failure of a Protractor test case to generate customized reports

Recently, I implemented Protractor testing for our Angular apps at the company and I've been searching for a straightforward method to record the pass/fail status of each scenario in the spec classes. Is there a simple solution for this? Despite my at ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...

Using Ajax to dynamically generate column headers in Datatables

Is there a way to create a header title from an ajax file? I've been trying my best with the following code: $('#btntrack').on('click', function() { var KPNo = $('#KPNo').val(); var dataString = & ...

Encountering issues with displaying images in React Next.js when utilizing dangerouslySetInnerHtml

While working on creating a simple WYSIWYG editor in nextjs, I encountered an issue with displaying uploaded images on the screen. When generating a blob URL for the image and using it as the src attribute of the image tag, it worked fine unless dangerousl ...

Exploring the depths of AngularJS through manual injection

I seem to have misunderstood the tutorial and am struggling to get manual injection working on my project. As I'm preparing to minify and mangle my JS code, I decided to manually inject all my modules and controllers. However, I keep encountering err ...

Developing a custom camera system for a top-down RPG game using Javascript Canvas

What specific question do I have to ask now? My goal is to implement a "viewport" camera effect that will track the player without moving the background I am integrating websocket support and planning to render additional characters on the map - movement ...

What could be causing the recurring appearance of the success alert message in an AJAX call to a PHP script in this particular situation?

Below you will find two code blocks, each designed to handle an AJAX call to a PHP file upon clicking on a specific hyperlink: <script language="javascript" type="text/javascript"> $(".fixed").click(function(e) { var action_url1 = $(th ...

What steps should I take to create an object that can be converted into a JSON schema like the one shown here?

I'm facing a rather simple issue, but I believe there's something crucial that I'm overlooking. My objective is to iterate through and add elements to an object in order to generate a JSON structure similar to the following: { "user1": ...