1

codesandbox link below

I am using react-date-range library that user can use to select start date and end date. After selecting the startDate and endDate, I am turning the output date to ISOString and when I send the date to BE, the date is incorrect. It's always one day late. Why is that and how can I fixed it?

If relevant in anyway, I am in Myanmar time zone which is GMT + 630

import { useState } from "react";
import moment from "moment";

import "./styles.css";
import "react-date-range/dist/styles.css"; // main style file
import "react-date-range/dist/theme/default.css";
import { DateRangePicker } from "react-date-range";
import { add } from "date-fns";

export default function App() {
  const [selectionRange, setSelectionRange] = useState({
    startDate: new Date(),
    endDate: new Date(),
    key: "selection"
  });

  const handleSelection = (range) => {
    setSelectionRange(range.selection);
  };

  const handleSend = () => {
    const { startDate, endDate } = selectionRange;

    const isoStartDate = startDate.toISOString();
    const isoEndDate = endDate.toISOString();

    console.log({ isoStartDate, isoEndDate });
  };

  return (
    <div className="App">
      <DateRangePicker ranges={[selectionRange]} onChange={handleSelection} />
      <button onClick={handleSend}>Send</button>
    </div>
  );
}


codesandbox demo

Steps to reproduce

  1. Select the start date and end date
  2. Click send and check the console
Nyi Nyi Hmue Aung
  • 587
  • 1
  • 7
  • 19
  • 1
    When you use toISOstring it, uses utc timezone "+0:00", so your db looks wait for your timezone, this causes this problem, A good trick is always uses UTC for all, and convert to clients in their views. – Aloiso Junior Oct 01 '22 at 14:17
  • Not exactly sure what you mean. But, DB is not involved at this point. I just sent the date to BE and checked the network tab, it's one day off. So, the issue is on FE. If I don't turn to toISOString(), it's correct. After transforming, console.log date is no longer correct. So, confusing. I would appreciate it if you can help, thanks – Nyi Nyi Hmue Aung Oct 01 '22 at 14:21
  • Not db okay, your languague such as PHP (for intance) can handle dates, and can have itself setted timezone. Please DB is just something to illustrate some scenario. – Aloiso Junior Oct 01 '22 at 14:23
  • Ok, Your browser have it's timezone, but js function (toISOstring) uses UTC timezone. So conversion is made. – Aloiso Junior Oct 01 '22 at 14:25
  • "*If I don't turn to toISOString(), it's correct*". Exactly. If a user with offset +10 does `new Date().toISOString()` before 10 am, they'll get a UTC date for the previous day. Similarly, if a user with offset -5 does the same thing after 7pm, they'll get a UTC date for tomorrow. This issue has been discussed a gazilllion times before. – RobG Oct 03 '22 at 02:33

0 Answers0