N.Esterl
N.Esterl

Reputation: 11

How can I get the weekday from an users input date?

function date() {
            var input = document.getElementById("input");

        }
<form>
    <input type="date" placeholder="dd:mm:yy" id="input"/>
    <input type="button" value="weekday" onclick="date()"/>
</form>
    <p id="output">

    </p>

How can I get the Weekday? I have tried many things and searched on google but haven't found anything. Thanks for help!

Upvotes: 1

Views: 7930

Answers (4)

Ani Menon
Ani Menon

Reputation: 28209

Code which takes inputs in the format mm/dd/yyyy :

<script>
  function day_of_week() {
    var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    var d = document.getElementById('date_input').valueAsDate;
    var n = d.getUTCDay()
    document.getElementById("output").innerHTML = weekday[n];
  }

</script>

<form>
  <input type="date" placeholder="dd:mm:yy" id="date_input" />
  <input type="button" value="Get Weekday" onclick="day_of_week()" />
</form>
<p id="output">

</p>

Upvotes: 3

Allen Fernandes
Allen Fernandes

Reputation: 1353

Whenever you use the HTML 5 input type = "date" format for date picker, you can directly get the value in date format,so no need to convert that to date format , also to set the value in your p tag with id="output" you can use the textContent method as shown below:

<form>
  <input type="date" placeholder="dd:mm:yy" id="selectedDate" />
  <input type="button" value="weekday" onclick="date()" />
</form>
<p id="output"></p>

function date() {
  var inputDate = document.getElementById("selectedDate").valueAsDate;
  var day = inputDate.getDay();
  var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  document.getElementById('output').textContent = (days[day]);
}

The getDay() function for date, gives you the number of the weekday of a given date,which is used as index position in weekdays names array.

Upvotes: 0

timolawl
timolawl

Reputation: 5564

You can do something like this:

function date() {
  var input = document.getElementById("input").value;
  var date = new Date(input).getUTCDay();
  
  var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
  
  document.getElementById('output').textContent = weekday[date];
}
<form>
  <input type="date" placeholder="dd:mm:yy" id="input" />
  <input type="button" value="weekday" onclick="date()" />
</form>
<p id="output">

</p>

Upvotes: 0

A.J.
A.J.

Reputation: 393

You're getting the element, you just need to grab the value.

var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

function date() {
  var input = document.getElementById("input");
  var date = new Date(input.value);
  var weekday = date.getDay();

  var output = document.getElementById("output");
  output.text = weekdays[weekday];
}

Upvotes: 0

Related Questions