This is my code which is validating the input and in dd-mm-yyyy but the show day function is changing it to mm-dd-yyyy and thus giving me wrong day. i have used console to check the output and if you want to see the code running https://jsfiddle.net/tjpvhwsc/1/ please input 12/01/1994 the output should be 12/01/1994 but it is showing 01/12/1994
function isValidDate(inputDate){
if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(inputDate))
return false;
var parts = inputDate.split("/");//12 01 1994
var day = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
var year = parseInt(parts[2], 10);
if(year < 1000 || year > 3000 || month == 0 || month > 12)return false;
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;
return day > 0 && day <= monthLength[month - 1];
}
class Inputdate extends React.Component {
state={
inputDate:'',
day:''
}
showDay=(inputDate)=>{
console.log(inputDate)
var d = inputDate.split("/\D/");
console.log("REceived date", d)
let dt = new Date(d).toLocaleString('en-GB')
console.log("new date", dt);
// const weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
// const weekday = dt.toLocaleString('en-GB')
// console.log("Formatted date", weekday);
// this.setState({day:weekday})
}
render() {
console.log(this.state)
return (
<div>
<input
name="date"
type="text"
value={this.state.value}
placeholder="dd/mm/yyyy"
onChange={(e)=> {
if(isValidDate(e.target.value)){
this.setState({inputDate : e.target.value})
}
else{
this.setState({inputDate : 'invalid date'})
}
}}
/>
<p>{this.state.inputDate}</p>
<div onClick={()=>this.showDay(this.state.inputDate)}>Show Day</div>
</div>
);
}
}
Use type="Date" and e.target.value will be formatted according to ISO-8601. For 12th January 1994 you will get 1994-01-12 which will be consistently parsed by new Date().
Or you could go 1 better and use e.target.valueAsDate and get an actual Date object representing the inputted date.
With type="date" the onchange handler will only be triggered for a valid date too.
function parseDate(){
const date = document.getElementById('date').valueAsDate;
console.log(date);
console.log(date.toLocaleDateString('en-GB'));
}
<input type="date" onchange="parseDate()" id="date">