Reputation: 69
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>
);
}
}
Upvotes: 3
Views: 1528
Reputation: 46161
You can use getDay()
, which returns a number from 0
to 6
, where 0
is for Sunday, 1
for Monday …
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
const numericDay = new Date("2023-09-25T10:42:01.058Z").getDay();
console.log(days[numericDay]);
Upvotes: 0
Reputation: 3272
This should work:
let d = new Date("12/01/1994")
const weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
let day = weekday[d.getDay()];
console.log(day)
Upvotes: 1
Reputation: 1487
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'))
Upvotes: 2
Reputation: 148
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)
Upvotes: 1