How can I parse a Date into my json file that's being sent to my db?

I'm learning backend with Nodejs and right now I'm connecting my backend with a MongoDB, I'm trying to create an object User that has Birth Date as one of it's properties, but I don't really know how to write the date part of the json in order to store it correctly.

I used the "dd-mm-yy" format:
I tried the "dd-mm-yyyy"

But when I send the petition it doesn't work. The object is created with the current date: enter image description here

I'm following a YT tutorial so I'm kinda lost on how I'm supossed to process the input json in order to make it into a date.

This is my post method, where I think I'll need to process the data in order to parse the String into a text but I'm honestly not sure:
enter image description here

If any of you guys could point me into the right direction I'd be very grateful!

Upvotes: 0

Views: 89

Answers (1)

h-sifat
h-sifat

Reputation: 1595

I think the date format is invalid. Whenever you're passing a date string of 3 parts separated by a delimiter e.g., "-" or "/" the format should be year-month-day.

But the date format I see from your example is day-month-year e.g., 28-11-1999. You need to convert that into the right format 1999-11-28. Here is a function to help you with that.

const invalidDate = "28-11-1999";

function formatDate(invalidDate) {
  return invalidDate.split("-").reverse().join("-");
}

const validDateString = formatDate(invalidDate);
const date = new Date(validDateString);

console.log("------The formatted date----------");
console.log(date);

// ------------------EDIT-------------------------
// By the way, you asked about processing that .json file
// If you're getting that file from users.json file
// then just import it. e.g., const users = require("users.json")

// But if you get it as a json string then you need to parse it.
// I'll assume you're getting it as a json string.

const userJsonString = `{
  "name":"Someone",
  "password":"A-bad-password",
  "birthdate":"28-11-1999"
  }`;

let user;
try {
  user = JSON.parse(userJsonString);
} catch (ex) {
  console.error("Invalid json string: " + ex.message);
}

console.log("--------Before formatting User----------");
console.log(user);

// Format user object
function formatUserObject(user) {
  const birthdate = user.birthdate;
  if (birthdate) user.birthdate = formatDate(birthdate);
}

formatUserObject(user);
console.log("--------After formatting User----------");
console.log(user);

Upvotes: 1

Related Questions