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

Kiee
  • 10,661
  • 8
  • 31
  • 56

2 Answers2

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();
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249