My code so far checks the date weather its valid or not but i don't know how to get the name of the day for the date i have input in the input field. For example : if i put 12/01/1994 it should print wednesday
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:''
}
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>
);
}
}
CodePudding user response:
This should work:
let d = new Date("12/01/1994")
const weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
let day = weekday[d.getDay()];
console.log(day)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var date = event.toLocaleDateString(undefined, options)
var day = date.split(',')[0] // This will show you the day name.
console.log(day)
CodePudding user response:
I think it is better practice to use toLocaleString
when you work with dates in javscript, for example, if you will try to use array where you have week days and get the specific string from that by your date format is bad, because on IOS you will get undefined
because "12/01/1994" is not a format supported by ECMA-262 so parsing implementation will be dependent and iOS will treat it as an invalid date.
const getWeekday = (dateFormat) => {
// split date in non-digit chaarcters
let [d, m, y] = dateFormat.split(/\D/);
//put them in Date method
const date = new Date(y, m - 1, d)
//and return weekday in long format
const weekday = date.toLocaleString("default", { weekday: "long" })
return weekday
}
console.log(getWeekday('12/01/1994'))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>