Detecting time range in ios using Swift [closed] - ios

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 6 years ago.
Improve this question
Lets say I have some rules for displaying a message like below
between 00:00-12:00 -> morning
between 12:01-14:00 -> noon
between 14:01-17:00 -> afternoon
between 17:00-23:59 -> evening
if current mobile time is between 00:00 and 12:00 I should get morning
How can I do that please guide.

This should do the job
func check(time: NSDate) -> String? {
let formatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
formatter.timeZone = NSTimeZone(name: "GMT")
guard let
beginNoon = formatter.dateFromString("12:00"),
beginAfternoon = formatter.dateFromString("14:00"),
beginEvening = formatter.dateFromString("17:00")
else { return nil }
if time.compare(beginNoon) == .OrderedAscending { return "Morning" }
if time.compare(beginAfternoon) == .OrderedAscending { return "Noon"}
if time.compare(beginEvening) == .OrderedAscending { return "Afternoon" }
return "Evening"
}
Test
check(formatter.dateFromString("10:00")!) // "Morning"
check(formatter.dateFromString("13:00")!) // "Noon"
check(formatter.dateFromString("15:00")!) // "Afternoon"
check(formatter.dateFromString("22:00")!) // "Evening"
Considerations
Your ranges are inconsistent
Here you are including the left and right boundaries
00:00-12:00 -> morning
here you are including only the right boundary
12:01-14:00 -> noon
14:01-17:00 -> afternoon
and here only the left boundary :)
between 17:00-23:59
In my code, the left boundary in only included while the right one is excluded.

Related

Swift compare dates iOS 15 [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 13 days ago.
Improve this question
Can anyone tell me why this doesn’t work right with dates from the server?
I'm trying to compare dates to Now so I can see what was in the past, today and future.
func getDetails(for game: Game) -> String {
let now = Date.now
let gameDate = game.gameDate
if gameDate.compare(now) == .orderedAscending {
print(“past”)
return "past"
}
if gameDate.compare(now) == .orderedDescending {
print(“future”)
return "future"
}
if gameDate.compare(now) == .orderedSame {
print(“today”)
return "today"
}
return "none"
}
My decoder is set decoder.dateDecodingStrategy = .iso8601
All of the dates come back “past” and this is iOS 15+
Thanks for your help in advance.
There is no reason to use the compare() function for dates. Dates conform to the Comparable and Equatable protocols, which means you can use >, <, = >=, and <= to compare them directly.
That said, we don't know what your game.date value is.
I can tell you that Date objects capture the date and time with sub-millisecond precision. Any date you pass into your function is likely to be a few nanoseconds before this code runs, and so be in the past.
consider this code:
let now = Date()
var total = 1
total *= 2
let later = Date()
let equalString = (now == later) ? "equal" : "not equal"
print("The dates are \(equalString)")
if now != later {
print("Dates differ by \(later.timeIntervalSinceReferenceDate - now.timeIntervalSinceReferenceDate)")
}
That code prints "The dates are not equal" because it takes enough time to multiply 1 * 2 that the later date is a tiny fraction of a second later than now.
(On my machine it says that the later date is greater than the now date by 8.499622344970703e-05, or about 8.4 microseconds.)
Take out the math code between the two statements and sometimes you'll get it to say the dates are equal, and other times it will say they are not equal.

Need unique dateformatter for single number (day & month) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Input: 9(Wed).12(Dec).2020
Day and month are represented by one number
I need date formatter for above input date string
You can try
func getDateFrom(_ str:String) -> Date? {
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "dd(EEE).MM(MMM).yyyy"
let date = dayTimePeriodFormatter.date(from: str)
return date
}
and call it getDateFrom("9(Wed).12(Dec).2020")

Milliseconds until midnight (local time) in Swift? [closed]

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 5 years ago.
Improve this question
I'm am writing an iOS app and I need to know the (whole) number of milliseconds until midnight (that is, 12:00:00.000 the next day) in the user's local time using Swift.
The application is in an expression like this:
let milliseconds_until_midnight : Int;
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(milliseconds_until_midnight)) {
//do_something
}
How can we do this? Addendum: the type must be Int, as UInt64 is not accepted in this particular situation.
You can use Calendar method nextDate(after:) to get the start of the next day, use Date method timeIntervalSince(date:) to find out the number of seconds until the next day and return it multiplied it by 1000:
extension Date {
var startOfNextDay: Date {
return Calendar.current.nextDate(after: self, matching: DateComponents(hour: 0, minute: 0), matchingPolicy: .nextTimePreservingSmallerComponents)!
}
var millisecondsUntilTheNextDay: TimeInterval {
return startOfNextDay.timeIntervalSince(self) * 1000
}
}
Playground testing:
let milliseconds = UInt64(Date().millisecondsUntilTheNextDay) // 7731021
Here is the code to count down number of seconds before midnight:
extension Date{
// code to get phone's time zone
var localTimeZoneName: String { return TimeZone.current.identifier }
var numberOfMilliSecondsUntilMidnight: TimeInterval?{
let todayDate = self
let tomorrowDate = todayDate.tomorrowAtMidnight
return tomorrowDate.timeIntervalSince(self) * 1000
}
// local time. beginning tomorrow at 12 AM
var tomorrowAtMidnight: Date{
var cal = Calendar.current
cal.timeZone = TimeZone.current
let today = cal.startOfDay(for: self)
return Calendar.current.date(byAdding: .day, value: 1, to: today)!
}
}
To call for anyone who is new to swift:
print(Date().numberOfMilliSecondsUntilMidnight)
I am pretty sure it works because I had to write a custom date class for a due date system.

How can i get a tableview to count a week 1 day per row (ex: monday jun 10th = row 1.. tuesday june 11th row 2) using swift [closed]

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 6 years ago.
Improve this question
How can i get a tableview to count a week 1 day per row (ex: monday jun 10th = row 1.. tuesday june 11th row 2) timestamped on a label using swift in xcode 7? i know how to get the current time but i need it to count 7 days and leave the date until the week starts over.
You should look at NSDateComponents and NSCalendar. For example if you're looking to get the dates of the current week starting Monday, you can say something like:
func datesForCurrentWeek() -> [NSDate]
{
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Weekday], fromDate: date)
let weekday = components.weekday == 1 ? 8 : components.weekday
var weekArray = [NSDate]()
for i in 2 ... 8
{
let components = NSDateComponents()
components.day = i - weekday
weekArray.append(calendar.dateByAddingComponents(components, toDate: date, options: [])!)
}
return weekArray
}
Here you just determine what the current day of the week is, and then create an array that includes it and the six other days that encompass that week. You also need to shift it so Monday is the start of the week, as Sunday is the default.
You can then create a property like "dateStringArray" to hold your dates as strings. For example:
let datesArray = datesForCurrentWeek()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .FullStyle
self.dateStringArray = datesArray.map{
dateFormatter.stringFromDate($0)
}
Then in your cellForRowAtIndexPath you can populate your cells:
cell.textLabel.text = self.dateStringArray[indexPath.row]
For more information on NSDateComponents see here and here.

How to get data from UIDatePicker - Swift [closed]

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 8 years ago.
Improve this question
I'm trying to get the data from the UIDatePicker, for example the user picked a date as 7:15 PM
How do I get the data from that so I can manipulate and use it for some other function?
If you have any questions or need any clarifications please comment them down below.
Add a handler for your UIDatePicker like so:
yourDatePicker.addTarget(self, action: #selector(DatePickerViewController.handler(sender:)), for: UIControl.Event.valueChanged)
And then do something like this in your handler:
#objc func handler(sender: UIDatePicker) {
let timeFormatter = DateFormatter()
timeFormatter.timeStyle = DateFormatter.Style.short
var strDate = timeFormatter.string(from: yourDatePicker.date)
// do what you want to do with the string.
}

Resources