How to loop through range of dates in Swift3 (for each day between x and y, call on a method and pass in that day as a date value) [closed] - swift

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to do the following:
for each day between startdate and enddate, call on this method and pass in that day as the date...etc.
This seems like something that should be straightforward but everything I'm trying is just not working out. I am unfamiliar with swift (this is a project I'm thrown into), but it seems like something as easy as a for loop is more complicated than I thought it was.
A lot of what I tried researching is either deprecate methods, or it's more focused on calculating days between two dates or something like that which I don't need.
p.s. I may need a fairly large range of dates (more than a year), so I think there would have to be consideration for things like leap years with certain methods?
If anyone can help that'd be really appreciated, thank you
Any additional info that I'm not sure if is relevant: I am using xcode version 9.4.1, ios 11.4. I have seen that people use c in these projects but I'm not too sure how that would work, it would be great to have just the swift code for this

This should be pretty simple. Just get the difference in days, create a range with it and loop through the number of days, add it to the start date and call your method. Note that I am using noon time as it is recommended for time insensitive calendrical calculations:
extension Date {
var noon: Date {
Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
}
let startOf2020 = DateComponents(calendar: .current, year: 2020, month: 1, day: 1).date!.noon
let now = Date().noon
let days = Calendar.current.dateComponents([.day], from: startOf2020, to: now).day! // 302
(0...days).forEach { n in
let date = Calendar.current.date(byAdding: .day, value: n, to: startOf2020)!
print(date.description(with:.current))
}

Related

Flutter how to add a 0 behind a hour if the hour is less than 10? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Im trying to check if an hour is below 10 so i can add a 0 behind it to make it the right hour format.
All my efforts till now haven't worked out.
Thank you for you time
You can use padLeft() method on strings. It takes width and padding parameters. You can use it like this:
print("5".padLeft(2,"0")); // Prints 05
print("14".padLeft(2,"0")); // Prints 14
you can try this;
var now = new DateTime.now();
String newHour = now.hour.toString();
if (newHour.length > 2) {
newHour = "0"+ newHour;
}

How to update a date set with a NSDatePicker in a way that is in the future and keeps the hours?

I'm trying to use an NSDatePicker to set a time when an event should happen. Unfortunately, however, this control is used to set a complete date and therefore it is possible that when I have to use the value, it belongs to the past. My goal is to use the datePicker to set a time in the future.
To create a future date preserving this time I tried to set a loop that adds a day until we get to a future point but this seems to be very expensive in terms of time and processing, or I tried to manually build a date using only time. Unfortunately, I do not think I have found a viable solution because of my lack of experience on the subject.
Here is the code I am using:
// getting date value from a NSDatePicker
let date = myDatePicker.dateValue
// learn if the date is in future or in past
if date.timeIntervalSince(currentDate as Date).sign == FloatingPointSign.minus {
print("\(date) is in past") // update adding days to make it in future
// get the hour and minute from the date
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm" // only hour and second
let timeString = timeFormatter.string(from: date as Date)
print("\(timeString)") // here I get "18:10" or "6:10 PM" based on system preferences (12 or 24)
// create a date in future that use this hours
} else {
// the date is already in future, just use it
...
}
I found several questions here on Stack Overflow, that are helping me to better understand how to use NSDateFormatter and also a great online tutorial http://www.knowstack.com/swift-nsdateformatter/. I also found some questions that seems similar to mine, like: returns a date an hour in the future and init] returning date an hour in the past? but they did not help me.
Apple Developer Documentation:
NSDatePicker
NSDateFormatter

yahoo finance API stopped working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Anyone else having problems with this API? I have just recently started working with it but suddenly everything that was working both mine and others is no longer working, first the CSV interface and now the YQL interface. Surprised I don't see any mention of this on this board or a google search.
You can still back out the periods since the interval is in seconds (60*60*24), one day = 86,400.
The cookie is the problem. This is how I did it in VBA: https://stackoverflow.com/a/44055850/8027976
Example for period 1:
Dim baseDate As Date: baseDate = #1/1/1970#
Dim period1 As Long: period1 = (startDate - baseDate) * 86400
Dim period2 As Long: period2 = (endDate - baseDate + 0.8) * 86400
You need the ".8", otherwise, it will not pull the end-of-day price.
Yes, it's not working anymore. They changed the coding so now it reads something like
https://query1.finance.yahoo.com/v7/finance/download/IWM?period1=1492465014&period2=1495057014&interval=1d&events=history&crumb=oL864EniL6D
evidently they want to plant a cookie so it's not possible to automate it. Also there is no clear equivalence between the period1 and period2 numbers and the dates (in this case 5/17/2016 and 5/17/2017 respectively) so you couldn't even program the dates.
I am not sure why. I am grateful for the years of downloading data, and I would love to have this ability restored.
The periods seem to be the number of seconds between epoch and the start of the day in UTC. In JavaScript the way to compute the periods is as follows:
new Date(2017,4,18).valueOf()/1000 - new Date(2017,4,18).getTimezoneOffset()*60

How to populate a calendar template with dates in the right place with Swift3?

I was thinking of finding the first day of the week and filling in from there, but how could I change the day number to be the 1st instead of the current? It sounded like calendar.firstWeekday might have done the trick but the docs say literally nothing about how it works and it returns 1 which definitely isn't Wednesday (Feb 1st, 2017). Tried changing now and calendar to vars and seeing if I could something along the lines of .setDay on them but haven't found anything.
let now = Date()
let calendar = Calendar.current
var components = calendar.dateComponents([.year, .month, .day, .weekday], from: date)
// 1 = Sunday, 7 = Saturday
print("day of week: ")
print(components.weekday)
However, using Swift's Date and Calendar, is there an easier way to do this than finding the first day and filling in the rest of the calendar from there? Is there a simpler way?
Foundation Calendar should allow you to do pretty much whatever you want.
If you want to get fancy, you could build something that takes a date and returns a Type (I would recommend a struct) with the date/weekday/etc. info in it for easy display/organization.

iPhone Date Picker rolls over to 2010 on December 27th?

So I implemented a UIDatepicker in one of my applications for scheduling and autodialing teleconferences... everything is pretty much ready to go except, while testing I noticed that when the date rolls over from December 26th to December 27th, the year changes to 2010.
I even rolled it forward to 2011... and it changes when December 25th changes to the 26th.... but wait... in 2012, it correctly rolls over on December 31 - January 1... and then its back to 29th-30th in 2013. Is there some kind of astronomical phenomenon I am not aware of going on or does Apple run on some crazy Heechee calendar I don't know of? The calendar app works correctly...
The most likely explanation is I am missing something so obvious that I will slap myself when I realize it. But hey, I haven't slept in... wow I don't remember if its been two days or three. Take pity and help me out here.
UPDATE: So maybe it wasn't something simple. Still looking for an answer here! Am I really the only person who has experienced this?? I'll bet when the end of December rolls around, more people will hit the same roadblock.
UPDATE2: Anyone? Still looking, still not finding...
UPDATE3: Still haven't found a solution. Come on! This is an interesting puzzle!
UPDATE4: Still no answer found. I have submitted the app and it is now in the appstore. Would still like to see this problem solved so I can update the app.
There may be this problem, that when you are on the last week of the month and the week has fewer than 7 days left in current month, then perhaps the API treated the week as the first week of the next month. Since december of 2012 has already 7 days in its last week there is no problem in that month.
I was getting the same problem here, and I solved it.
- (int) currentWeekOfMonth
{
return CFCalendarGetOrdinalityOfUnit (
CFCalendarCopyCurrent(),
kCFCalendarUnitWeek,
kCFCalendarUnitMonth,
[self absoluteTime]);
}
my requirement is to show week number and for this i calculate the week number of first week of month and the add this to the total number of week in month.
int currentWeekNumberInYear = [_calendarInfo currentWeekOfYear];
int currentWeekNumberInMonth = [_calendarInfo currentWeekOfMonth];
currentWeekNumberInYear = currentWeekNumberInYear-currentWeekNumberInMonth +1;
currentWeekNumberInYear = currentWeekNumberInYear<0 ? (NSInteger)[_calendarInfo weeksInMonth] ==5 ?49:48 : currentWeekNumberInYear;
I hope it will be useful to you.
Turns out its the Date format string used to set up the NSDateFormatter that was causing this for me.
"yyyy" corresponds to the 4-digit year, while YYYY corresponds to the year starting from the Sunday of the 1st week of year. Why anyone would want this is anyone's guess, and it would really help if Apple provided a link to their list of format specifiers, but there you go.
Just make sure your format string has the year component in lowercase and it should be sorted.
This post on TUAW describes a similar problem in PhotoBooth on Mac OS X:
http://www.tuaw.com/2009/12/29/beware-photo-booth-time-stamps-its-a-bug-not-a-feature/
One commenter agrees with vikas that it's an end-of-week issue.