Categories
JavaScript

Date

  • Copy / clone a Date object
// Method 1
const date = new Date();
const copiedDate = new Date(date.getTime());

// Method 2
const date = new Date();
const copyOfDate = new Date(date.valueOf());

// Method 3 - update for 2021
const date = new Date();      //  with or without an argument
const date2 = new Date(date); //  clone original date

// Method 4
const orig = new Date();
const copy = new Date(+orig);

getTime() method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC

+ sign is unaray operator here. It means new Date(Number(orig))

https://stackoverflow.com/questions/1090815/how-to-clone-a-date-object

  • Update a state object with Date type in React
const [myDate, setMyDate] = useState(new Date());

setMyDate(date => {
    date.setDate(date.getDate() + 1);
    return new Date(date)
});

Return a different object in setMyDate so that React can tell it has been modified

https://stackoverflow.com/questions/72388233/adding-a-day-to-react-state-date-object-created-using-usestate

Leave a comment