3

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>
    );
  }
}
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • try use normal new Date() [getDays()](https://www.w3schools.com/jsref/jsref_getday.asp) – Eka Cipta Nov 30 '21 at 10:30
  • Does this answer your question? [How to get the day of week and the month of the year?](https://stackoverflow.com/questions/4822852/how-to-get-the-day-of-week-and-the-month-of-the-year) – Aidan Donnelly Nov 30 '21 at 10:37

3 Answers3

2

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'))
callmenikk
  • 1,358
  • 2
  • 9
  • 24
  • please check this one https://jsfiddle.net/Abhishek_12/0tkcL973/6/ it is converting my input date dd-mm-yyyy to mm-dd-yyyy thus giving wrong answer – talent in making Nov 30 '21 at 16:50
  • You must use spread operator when you update state you don't save previous actions that means when you trigger `onChange` value still becomes `""` you must try like that onChange `this.setState({...this.state, inputDate : e.target.value})}` you update state with new value and save that previous ones, and after date format include my function and return new value in that state you can check working example in code, here is **[JSFIDDLE](https://jsfiddle.net/callmenikk/L4k36qf1/17/)** – callmenikk Nov 30 '21 at 19:01
  • can you please explain this line what this line is actually doing const date = new Date(y, m - 1, d) specially this part new Date(y, m - 1, d) – talent in making Nov 30 '21 at 19:21
  • what it does and I split your string in non digit characters it doesn't matter what will be between numbers this `-`, `/`, or even this `%`, **it does't matter**, I create array with 3 string, these are day that a marked as `d` - day `m` - month `y` - year so if your data string is 11/30/2021 that part will return `[11, 30, 2021]`, to use that, array in date, javscript must read that as `year`, `month`, `day`, why I make on month `m -1`? because in javscript first month is january and index will `0`, so if november is 11th month, for js it will be 10, and pass I there `2021 10 30` – callmenikk Nov 30 '21 at 19:41
  • One more thing in my validate function I have used regex to validate the date is there are any other ways to do that. If yes please help me with that because I find regex a bit tough. But thanks for the above explanation. – talent in making Nov 30 '21 at 19:56
  • yes you can use `.split("/")` method which will split that string in `/` this character, `"11/12/2021" -> [11, 12, 2021]` but it will work on only `/` if your string will includes any other character for example `-` this, it wont split that, you will need to use `.split("-")` this so it will work well, but if you work with lots of non-digit characters I would recommend you to use regex, cheers – callmenikk Nov 30 '21 at 20:29
1

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)
Reinier68
  • 2,450
  • 1
  • 23
  • 47
  • 1
    `const weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", Saturday"]` – kiranvj Nov 30 '21 at 10:40
  • 1
    Can I place the inputDate variable instead of hard coding the date ? – talent in making Nov 30 '21 at 10:44
  • @AbhishekRoy Yes, in your code you mention this: `var parts = inputDate.split("/"); //12 01 1994`. So use that with my code and then that should work. So something like this `const d = new Date(parts)` or something. – Reinier68 Nov 30 '21 at 10:47
  • suppose i have put 12-01-1994 after spliting when i m passing it through the date function the format becomes dec-01-1994 and thus giving me wrong day how to convert that format to dd-mm-yyyy because when m giving an input 30/11/2021 its returning NAN – talent in making Nov 30 '21 at 12:56
  • @AbhishekRoy Could you recreate your code on codesandbox / jsfiddle or something? Then I can have a look. – Reinier68 Nov 30 '21 at 13:24
  • @Reinier68 https://jsfiddle.net/Abhishek_12/uq2tnxm9/13/ i have consoled the outputs for now so click on the Show day to get the result in console – talent in making Nov 30 '21 at 14:01
  • @AbhishekRoy here you go: https://jsfiddle.net/ak27L845/6/ . One thing to note tho, I changed the date format to `mm/dd/yyyy`, cuz that what the date object expects. You can easily change this around by chaning the format: https://stackoverflow.com/questions/11591854/format-date-to-mm-dd-yyyy-in-javascript – Reinier68 Nov 30 '21 at 19:31
1
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)
Muhammad Hasher
  • 148
  • 1
  • 8