Kiee
Kiee

Reputation: 10771

Get day of date string with javascript

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

Upvotes: 2

Views: 2329

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201419

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.

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

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();

Upvotes: 4

Related Questions