Home > other >  Get the Date from DateTime object String in JSON response from backend
Get the Date from DateTime object String in JSON response from backend

Time:02-19

I am working on a React JS project where my state is getting updated with date object string from the backend JSON response. I am getting a Date Time object in form of a string which looks like this:

createDateTime: "2022-02-08T14:17:44"

The "createDateTime" object is assigned to my react js state, but when I show that updated state in the Browser UI, I get this:

2022-02-08T14:17:44

I want to display just the date, not the time stamp that comes along with the JSON string response. Is there any method that I can use to display just the Date?

2022-02-08

CodePudding user response:

I would create some helpers to show exactly what you need. How about something like this?

function DateTimeParser(date?: string) {
  if (date === undefined) return date;
  const dateTime = new Date(date);
  const parsedDate = `${dateTime.getDate()} ${
    dateTime.getMonth()
  } ${dateTime.getFullYear()}`;
  return parsedDate;

You can amend this to show exactly what you need.

CodePudding user response:

Calling toLocaleDateString on your date value should get the result you want but first of all, you will need to parse the date you get from the server:

const parsedDate = new Date(responseDate)
const date = parsedDate.toLocaleDateString()

You can optionally pass to toLocaleDateString() the desired locale (in case you want to get the date in the format which differs from your local one)

  • Related