Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Get Yesterdays Day of Week

Tags:

javascript

I have a string that contains a day of the week (ex "Monday"). I need to figure out how to take this string and get the previous day of the week.

For example if the string contains "Monday" the new string should output "Sunday".

I feel like there is a simple solution (that isn't 7 IF statements) that I'm missing here.

like image 489
WolfieeifloW Avatar asked Nov 29 '19 21:11

WolfieeifloW


Video Answer


3 Answers

Try

let yesterday = {
  'Monday': 'Sunday',
  'Tuesday': 'Monday',
  'Wednesday': 'Tuesday',
  'Thursday': 'Wednesday',
  'Friday': 'Thursday',
  'Saturday': 'Friday',
  'Sunday': 'Saturday',
}

console.log(yesterday['Monday']);
like image 79
Kamil Kiełczewski Avatar answered Oct 17 '22 04:10

Kamil Kiełczewski


One straightforward approach, assuming correct input, would be using arrays:

days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
previousDay = days[(days.indexOf(currentDay)-1+7)%7];
like image 6
Yaniv Avatar answered Oct 17 '22 05:10

Yaniv


You can use indexOf and return Sun when you exceed array range:

let currentDay = "Mon";

let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
let prevDay = days[days.indexOf(currentDay) - 1 ] || "Sun";

console.log(prevDay);
like image 3
mickl Avatar answered Oct 17 '22 04:10

mickl