2

I cant find a way of getting the day from a date string. The format of the string is dd/mm/yyyy and I want to use getDay() to get the current weekday.

Is this possible? I know i'd have to convert my string to a Date object but cant find a list of accepted formats

2
  • possible duplicate of javascript Date.parse Commented Jun 16, 2014 at 14:06
  • "I know I'd have to convert my string to a Date object". Eh, yes. Commented Jun 16, 2014 at 14:19

2 Answers 2

4

Sometimes, problems are a lot simpler than they seem.

var date = "16/06/2014";
var dayOfDate = date.substr(0,2);

If a single-digit day is possible, try this:

var date = "5/6/2014";
var parts = date.split("/");
var dayOfDate = parts[0];

And sometimes, it pays to read the question >_>

Continuing from the second option above:

var dateObj = new Date(parts[2], parts[1]-1, parts[0]);
// parts[1]-1 because months are zero-based
var dayOfWeek = dateObj.getDay();
Sign up to request clarification or add additional context in comments.

1 Comment

OP wants the day (0-6), not the date.
3

Since Date.prototype.parse() doesn't seem to support that format. I would write a parseDate(),

function parseDate(input) {
  var parts = input.split('/');
  // Note: months are 0-based
  return new Date(parts[2], parts[1]-1, parts[0]);
}
function getName(day) {
    if (day == 0) return 'Sunday';
    else if (day == 1) return 'Monday';
    else if (day == 2) return 'Tuesday';
    else if (day == 3) return 'Wednesday';
    else if (day == 4) return 'Thursday';
    else if (day == 5) return 'Friday';
    return 'Saturday';
}
var d = parseDate('16/06/2014');
var weekday = d.getDay();
var weekdayName = getName(weekday);

and JSFiddle.

1 Comment

getName could be much simpler as return ["Sun","Mon","Tues","Wednes","Thurs","Fri","Satur"][day]+"day";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.