automatically update label every week - ios

So I was wondering, how could I update a specific label once every week. I have a recipe app and want to present the user with new recipe once a week, i would get the recipe name from an Array
var recipeArray = ["Pasta, Fish, Meatballs"]
var weekNumber = 0
func weeklyRecipe () {
//trigger once a week
if weekNumber <= (recipeArray.count - 1) {
weekNumber += 1
} else {
weekNumber = 0
}
label.text = recipeArray[weekNumber]
}
I have no idea how to work with calendar, and will appreciate any help on the topic.

You can update recipe on any particular day. Suppose you want to update on Sunday. Then
let weekday = Calendar.current.component(.weekday, from: Date())
if weekday == 1 {
// Code for updation
}

Related

How to include lastmonth last week in this months first week using ASP.Net MVC

I wrote a code that brings up Current Month Data and groups it by Week. This is great, but the issue here is that I want to also include Last month's Last weekdays in First Week for This month. The reason being the Current Month date is April 01st, 2021, but I am looking to group data for an entire week.
Here is the example
March Week 4 Starts on 29th March, which falls on Monday
Aprile Week 1 Starts on 01st April, which falls on Thursday.
So, If the Current Month First Week Number of Days is greater than Last Month Last Week Number of Days, how can I group the data in as April First Week which should be from March 29th TO April 04th.
The same shall continue for May, April Last Week has 5 days, and May First week has 2 days. Hence, the grouping should display data for Last Week Aprile and not in First Week May
Action Method
public ActionResult DisplayChart()
{
/*This Month Begin*/
DateTime now = DateTime.Now.AddDays(-3);
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
/*This Month Ends*/
var result = db.Chats.Where(c => System.Data.Entity.DbFunctions.TruncateTime(c.MSTChatCreatedDateTime) >= startDate &&
System.Data.Entity.DbFunctions.TruncateTime(c.MSTChatCreatedDateTime) <= endDate).Select(x => new {x.MSTChatCreatedDateTime}).ToList().GroupBy(c => new
{
Year = c.MSTChatCreatedDateTime.ToCleanDateTime().Year,
Month = c.MSTChatCreatedDateTime.ToCleanDateTime().Month,
WeekofMonth = c.MSTChatCreatedDateTime.ToCleanDateTime().GetWeekOfMonth()
}).Select(c => new ReportVM
{
Title = string.Format("{0}/{1}/Week{2}", c.Key.Year, c.Key.Month, c.Key.WeekofMonth), //chart x Axis value.
ChatCountCreatdDate = c.Count() //chart y Axis value.
}).ToList();
//return the data to the view.
return View(result);
}
Thank you in advance
try this:
public class MyModel
{
public DateTime? Date { get; set; }
public string GroupBy
{
get
{
if (Date.HasValue)
{
DateTime nowDate = DateTime.UtcNow;
if (nowDate.ToString("dd/MM/yyyy") == Date.Value.ToString("dd/MM/yyyy"))
{
return "Today";
}
else if (nowDate.AddDays(-1).ToString("dd/MM/yyyy") == Date.Value.ToString("dd/MM/yyyy"))
{
return "Yesterday";
}
else if ((nowDate - Date.Value).TotalDays <= 7)
{
return Date.Value.DayOfWeek.ToString();
}
else if ((nowDate - Date.Value).TotalDays <= 14)
{
return "Last Week";
}
else if ((nowDate - Date.Value).TotalDays <= 21)
{
return "Two Weeks Ago";
}
else if ((nowDate - Date.Value).TotalDays <= 28)
{
return "Three Weeks Ago";
}
else if (nowDate.TotalMonths(Date.Value) == 1)
{
return "Last Month";
}
else
{
return "Older";
}
}
return string.Empty;
}
}
}

Sheet showing available hours between everyone

I want to create a spreadsheet where I can add people on it and see which hours everyone is available to do a online meeting. It's mandatory to consider the timezone but I have no clue how to do it.
Person1 sheet example:
Matching hours:
I think my idea of showing 'matches 4 out of 5' is nice, cause the remaining one can make an effort to show up and edit it so it can be like 'matches 5 out of 5'. But any other suggestion is welcome.
The link of the actual spreadsheet(copy to your own drive so you can edit): https://docs.google.com/spreadsheets/d/1yun8uMW2LZUumlm6cy3hqPT-FLQipADSIjLQPNiwXl4/edit?usp=sharing
PS: It would be nice to support DST (daylight save time) but it's not mandatory. The person who is in DST will adjust it.
Assuming your timezone values are all offsets of the Match Sheet (if the match sheet says 01:00 and your timezone is -1, your local time would be 00:00), here is some code that will show you the text in the way that you want:
function availablePeople(startTime, dayOfWeek) { //All slots are 1 hour long
const sheetsNames = ["person1", "person2", "person3", "person4"]; //Edit this to update possibilities
const dayHeaderRow = 2;
const startTimeCol = 1;
const endTimeCol = 2;
var sheets = SpreadsheetApp.getActive();
var referenceHourRow = sheets.getSheetByName("match").getRange(dayHeaderRow+1, startTimeCol, 24).getValues().map(function (x) {return x.toString()}).indexOf(startTime.toString());
var referenceDayCol = sheets.getSheetByName(sheetsNames[0]).getRange(dayHeaderRow, endTimeCol+1, 1, 7).getValues()[0].indexOf(dayOfWeek);
var availablePeople = 0;
if (referenceHourRow != -1) {
for (var i = 0; i<sheetsNames.length; i++) {
var personSheet = sheets.getSheetByName(sheetsNames[i]);
var timezone = -personSheet.getRange(1, 4).getValue();
var thisDayCol = referenceDayCol;
var thisHourRow = referenceHourRow;
if (timezone!=0) {
if (thisHourRow+timezone<0) {
//Went back a day.
thisDayCol = (thisDayCol+6)%7;
thisHourRow = 24-(referenceHourRow-timezone);
} else if (thisHourRow+timezone>=24) {
//Went forward a day
thisDayCol = (thisDayCol+1)%7;
thisHourRow = (thisHourRow+timezone)%24;
} else {
thisHourRow += timezone;
}
}
var cell = personSheet.getRange(dayHeaderRow+1+thisHourRow, endTimeCol+1+thisDayCol);
if (cell.getValue()=="Available") {
availablePeople++;
}
}
}
return availablePeople+" out of "+sheetsNames.length;
}
This is how to use this function: =availablePeople(<START TIME>,<DAY OF THE WEEK>).
To allow this to be dragged and autocompleted, write =availablePeople($A3,C$2) in the "Monday" "00:00" and then drag it horizontally and vertically to update the formula.

Modifiy child constantly by using the UploadDate

I am currently building an Instagram clone.
I am quit new so please forgive me if this question is answered easily.
I just want to have a specific score attached to each post.
I already managed to give each new post a score 0f 0 to start with and each time its liked it increases by 100, disliked it decreases by 100.
for every comment it grows by 50 points.
Because I want to order them smartly and want it to show different posts at the top over time I wanted to include a third variable which influences the score.
I want it to decrease the score by -10 each hour since its been uploaded.
The increase and decrease is done in my function incrementLikes() /incrementComments() .
I know that I can't modify the value of score for the time since its uploaded there, but I don't know where else.
My date extension (prob where I can do it?)
extension Date {
func timeAgoDisplay() -> String {
let secondsAgo = Int(Date().timeIntervalSince(self))
let minute = 60
let hour = 60 * minute
let day = hour * 24
let week = day * 7
let month = week * 4
let quotient : Int
let unit: String
if secondsAgo < minute {
quotient = secondsAgo
unit = "Sekunde"
} else if secondsAgo < hour {
quotient = secondsAgo / minute
unit = "Minute"
} else if secondsAgo < day {
quotient = secondsAgo / hour
unit = "Stunde"
} else if secondsAgo < week {
quotient = secondsAgo / day
unit = "Tage"
} else if secondsAgo < month {
quotient = secondsAgo / week
unit = "Woche"
} else {
quotient = secondsAgo / month
unit = "Monat"
}
return "Vor \(quotient) \(unit)\(quotient == 1 ? "" : "n")"
}
}
my function in homeTableViewCell where I set the date
func updateView() {
captionLabel.userHandleLinkTapHandler = { label,string, range in
let mention = String(string.characters.dropFirst())
API.User.observeUserByUsername(username: mention.lowercased(), completion: { (user) in
self.delegate?.goToProfileUserViewController(userId: user.id!)
})
}
guard let count = post?.commentCount else {return}
if count == 0 {
commentButton.setTitle("Schreibe den ersten Kommentar", for: UIControlState.normal)
}else if count == 1 {
commentButton.setTitle("Sieh dir den ersten Kommentar an", for: UIControlState.normal)
} else {
commentButton.setTitle("Alle \(count) Kommentare ansehen", for: UIControlState.normal)
}
let timeAgoDisplay = post?.creationDate?.timeAgoDisplay()
timeLabel.text = timeAgoDisplay
}
thanks for your help :)
The idea of updating the score every hour using a time is based on the idea that the app is constantly running, which seems flawed.
You could instead have something like
var score: Int {
return likes*100 - dislikes*100 + comments*50 - hoursSinceUpload()*10
}
where hoursSinceUpload is computed by something like (see Getting the difference between two NSDates in (months/days/hours/minutes/seconds) for reference)
func hoursSinceUpload() -> Int {
return Calendar.current.dateComponents([.hour], from: uploadDate, to: Date()).hour
}

How to determine if a business is open given the hours of operation (Swift-iOS)

I have an app that I'm building in Swift that needs to determine if a store/restaurant is currently open. It queries a database that I have control of, so I can set the open hours however I'd like. Currently I have an openTime/closeTime column for each day of the week set as a timestamp. For example: MonOpen = 11:00, MonClose = 19:00.
How can I use swift to determine if the place of business is currently open? I'm imagining something like if currentTime > MonOpen & currentTime < MonClose {...
An example of this is the iOS Starbucks app. If you go to locations, each location is listed with an "Open until 22:00" or "Open until 23:00."
It's just a matter of playing with the timezone, whether you use the user system's timezone or let them choose another one in the app's settings:
let tz = NSTimeZone.defaultTimeZone()
let now = NSCalendar.currentCalendar().componentsInTimeZone(tz, fromDate: NSDate())
if now.weekDay == 2 && now.hour > MonOpen && now.hour < MonClose {
// The store is open
}
I would like to take another crack at this question since we now have Swift 5.1 and most businesses have more complex opening times than just in hours.
import Foundation
// There might be an enum in Swift
// that I did not bother to lookup
enum Days : Int {
case Sun = 1
case Mon = 2
case Tue = 3
case Wed = 4
case Thu = 5
case Fri = 6
case Sat = 7
}
func isOfficeOpenNow(weekSchedule: [Days: (Int, Int)]) -> Bool {
let tz = NSTimeZone.default
let now = NSCalendar.current.dateComponents(in: tz, from: Date())
guard let weekday = now.weekday,
let today = Days(rawValue: weekday),
let hour = now.hour,
let minute = now.minute else {
return false
}
guard let todayTuple = weekSchedule[today] else {
return false // no key, means closed
}
let opensAt = todayTuple.0
let closesAt = todayTuple.1
assert(opensAt < closesAt, "Your schedule is setup wrong.")
let rightNowInMinutes = hour * 60 + minute
return rightNowInMinutes > opensAt &&
rightNowInMinutes < closesAt
}
To use this just define a dictionary for each day.
Key is the dayofweek. Could have used a string "Mon","Tue",etc
but then you will need a mapping or DateFormatter
Value is a tuple (int, int) for (open, close) in minutes
Using minutes, as many stores have more complex open
closing times than just hours
let schedule = [
Days.Mon: (9*60+30, 22*60+30),
Days.Tue: (9*60+30, 23*60+05),
Days.Wed: (9*60+30, 22*60+30),
Days.Thu: (9*60+30, 22*60+30),
Days.Fri: (9*60+30, 22*60+30),
]
if isOfficeOpenNow(weekSchedule: schedule) {
print("Store open")
} else {
print("Store closed")
}
If a specific week is a holiday, just update the schedule for the week and all is good with the world.
If a day is closed, just remove the key from the schedule.

How To Get Thursdays Of Year Using Carbon

I want to get all the Thursdays of a year using Carbon and save it on DB.
so far I could only store the Thursdays of current month. please advice me how to make it for the whole year once.
Current code :
public function getThursdays()
{
return new \DatePeriod(
Carbon::parse("first thursday of this month"),
CarbonInterval::week(),
Carbon::parse("first thursday of next month")
);
}
public function handle()
{
$thursdays = $this->getThursdays();
foreach ($thursdays as $thursday)
{
$Weeks = new Week();
$Weeks->week_starting_date = $thursday;
$Weeks->save();
}
}
You can get the number of weeks per year firstly using WEEKS_PER_YEAR, e.g :
$weeks_per_year = Carbon::WEEKS_PER_YEAR;
After that get the first thursday of year using :
$first_thursday = Carbon::parse("first thursday of this year");
Then loop through all the weeks adding every time one week using Carbon function addWeeks(1) to get the thursday of the next week and so :
for($i=1;$i<$weeks_per_year;$i++)
{
array_push( $thursdays, $first_thursday->addWeeks(1)->toDateString() );
}
FULL code :
$weeks_per_year = Carbon::WEEKS_PER_YEAR;
$first_thursday = Carbon::parse("first thursday of this year");
$thursdays = [$first_thursday->toDateString()];
for($i=1;$i<$weeks_per_year;$i++)
{
array_push( $thursdays, $first_thursday->addWeeks(1)->toDateString() );
}
Output :
An array of all the year thursdays in following format yyyy-mm-dd :
["2016-01-07","2016-01-14","2016-01-21", ... ,"2016-12-29"]
Or you can store dates directely in you DB instead of returning an array like :
for($i=1; $i<$weeks_per_year;$i++){
$Weeks = new Week();
$Weeks->week_starting_date = $first_thursday->addWeeks(1)->toDateString();
$Weeks->save();
}
Hope this helps.

Resources