0

I'm creating a simple expenses fullstack react app. In this app, users enter a description, amount, and date for a particular expense item. This expense item or the "Budget" state is saved in the back-end. Now, whenever the user loads the page, a GET request is made to retrieve "Budget" and is outputted to a table and a line graph.

The issue is when the user inputs their date it is formatted like this:

Sun May 24 2020 14:53:20 GMT-0400 (Eastern Daylight Time)

When the date is posted to the back-end and retrieved to the UI, it looks like this:

2020-05-24T04:56:12.000Z

I reformat the date retrieved from the back-end to this: DD-MM-YYYY. However, when the user submits the date it will look like this ay 24. Now, if the user refreshes the page it will reformat to what I want (i.e. DD-MM-YYYY). So, the date format looks incorrect until the page is refreshed.

Here is the MongoDB model for budget:

const budgetSchema = mongoose.Schema(
  {
    desc: {
      type: String,
    },
    amount: {
      type: Number,
    },
    date: {
      type: Date,
    },
  },
  { timestamps: true }
);

Here is the full code:


import "react-datepicker/dist/react-datepicker.css";


export default function Budget() {
  const [Balance, setBalance] = useState([0]);
  const [Income, setIncome] = useState(0);
  const [Expense, setExpense] = useState(0);

  const [Input, setInput] = useState([]);
  const [Description, setDescription] = useState("");

  const [startDate, setStartDate] = useState(new Date());

  const [Budget, setBudget] = useState([]);

  const [loadingBudget, setloadingBudget] = useState(true);

  useEffect(() => {
    axios
      .get("API Path")
      .then((response) => {
        if (response.data.success) {
          // console.log(JSON.stringify(response.data, null, 2));
          setBudget([...Budget, ...response.data.budget]);
        } else {
          alert("Failed to get save Budget");
        }
      });
    setloadingBudget(false);
  }, []);

  const dates = Budget.sort(function (a, b) {
    var dateA = new Date(a.date),
      dateB = new Date(b.date);
    return dateA - dateB;
  }).map((i) => {
    return (
      i.date.toString().substring(5, 10) +
      "-" +
      i.date.toString().substring(0, 4)
    );
  });

  const charges = Budget.map((i) => {
    return i.amount;
  });


  const handleChange = (e) => {
    setInput(e.target.value);
  };

  const handleDate = (date) => {
    setStartDate(date);
  };

  const handleDescription = (e) => {
    setDescription(e.target.value);
  };

  const handleClick = (e) => {
    e.preventDefault();
    if (Input > 0) {
      setIncome(Input);
    } else {
      setExpense(Input);
    }
    let val = parseInt(Input, 10);
    setBalance([...Balance, val]);
    setBudget([
      ...Budget,
      {
        desc: Description,
        amount: val,
        date: startDate,
      },
    ]);
    const variable = {
      desc: Description,
      amount: val,
      date: startDate,
    };
    axios
      .post("API Path", variable)
      .then((response) => {
        if (response.data.success) {
          console.log(response.data);
          setInput("");
          setDescription("");
          setStartDate("");
        } else {
          alert("Failed to save Budget");
        }
      });
  };

  return (
    <React.Fragment>

      <div style={{ backgroundColor: "#f2f2f2" }}>
        <div>
          <br />
          <BudgetForm
            Description={Description}
            handleDescription={handleDescription}
            Input={Input}
            handleChange={handleChange}
            startDate={startDate}
            handleDate={handleDate}
            handleClick={handleClick}
          />
        </div>
        {!loadingBudget && <Chart dates={dates} charges={charges} />}
      </div>
    </React.Fragment>
  );
}

I'm assuming that the answer deals with how startDate is initialized to new Date(). This would mean that it is formatted to what I don't want. Therefore, I would suspect that if I format startDate before it is sent to the back-end, it should work correctly? I know from previous stackoverflow questions a solution like this would work:

var d = new Date ()
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; 
var curr_year = d.getFullYear();
console.log(curr_month + "-" + curr_date + "-" + curr_year);

However, I'm not sure where I could implement this. Any suggestions would be great!

traveler316
  • 97
  • 3
  • 11

1 Answers1

0

Dates in servers should be in UTC time. And you should convert the date to local timezone in the client-side this can be done with new Date(fetchedDateStringinUTC). Feed this to your react component.

For more info this answer provides good context. https://stackoverflow.com/a/31453408/13283982

carlosbf
  • 78
  • 3