Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

44
Views
Date from string treated as wrong format

I had a string value = "01/08/2021 - 31/08/2021" and i need to get the starting date using value.substring(0,10) which return as 01/08/2021. But when i converting it to date using new Date(value.substring(0,10)) it convert the date format as 2021-01-08(yyyy-mm-dd).

Any help on this ?

7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

Split into the year, month and day

const [day, month, year] = value.substring(0,10).split('/');

Use the Date constructor

new Date(year, month - 1, day);
7 months ago · Juan Pablo Isaza Report

0

JavaScript date decodes your date string to "mm/dd/yyyy" format. You can simply split your date string to month - mm, date - dd and year - yyyy and provide this to date object.

Please Note: Dont forget to reduce 1 from the month number. Because JavaScript date counts month from 0 to 11.

const value = "01/08/2021 - 31/08/2021";
//  const startDate = value.substring(0,10);
const [startDate, endDate] = value.split(" - ");
const [dd, mm, yyyy] = startDate.split("/");
console.log(startDate);
console.log(new Date(yyyy, +mm - 1, dd).toDateString());

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs