0

I'd like to have my date in a dd-mm-yyyy format, so I wrote the below in order to reassemble the date I get from my date picker. Instead of getting 17-05-2021, I'm getting 1,7-0,5-2,0,2,1 What can I do to avoid those commas?

I'm open to other suggestions on how to get this date in a more efficient way than what I wrote

  const minDate = new Date().toISOString().slice(0, 10) // outputs 2021-05-17

  const [text, setText] = useState('');
  const [urgent, setUrgent] = useState(false);
  const [date, setDate] = useState(minDate);

  const formatDate = () => {
    let tempDate = [...date];
    let day = tempDate.slice(8);
    let month = tempDate.slice(5, 7);
    let year = tempDate.slice(0, 4);
    let newDate = `${day}-${month}-${year}`;
    return newDate;
  };

  const handleSubmit = () => {
    let fixedDate = formatDate(date);
    console.log(newDate) // outputs 1,7-0,5-2,0,2,1
    if (text.length > 5) {
      props.addTask(text, urgent, fixedDate);
      setText('');
      setUrgent(false);
      setDate(minDate);
    } else alert('Task name too short!');
  };

The date picker

<input
   type="date"
   min={minDate}
   value={date}
   onChange={(event) => setDate(event.target.value)}
/>
bysiuxvx
  • 65
  • 2
  • 10

3 Answers3

0

const formatDate = (dateStr) => {
    const [year, month, day] = dateStr.split('-');
    let newDate = `${day}-${month}-${year}`;
    return newDate;
  };
  
const formattedDate = formatDate('2021-01-31');

console.log(formattedDate);
Vaibhav Vishal
  • 6,576
  • 7
  • 27
  • 48
  • 1
    Didn't think about deconstructing it and putting it as a global function not only for this case, thanks, very cool. I understood the formatDate('2021-01-31') part, others didn't and I think that's why they downvoted – bysiuxvx May 17 '21 at 19:00
0

you can define the formatDate function like belows.

const formatDate = date => `${date.getDate().toString().padStart(2, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getYear()}`;
TopW3
  • 1,477
  • 1
  • 8
  • 14
0

You can use split and join like this without having to change your code;

 const formatDate = () => {
    let tempDate = [...date];
    let day = tempDate.slice(8);
    let month = tempDate.slice(5, 7);
    let year = tempDate.slice(0, 4);
    let newDate = `${day}-${month}-${year}`;
    return newDate.split(',').join('');   // Change This Line
  };

this will remove comas.

İlker
  • 1,872
  • 1
  • 12
  • 28