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.
Related
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 6 years ago.
Improve this question
Click here to see the imageI am having the times on two button on its title I am having the two time with AM/PM.
I have tried so many ways to subtract the times between these two buttons but not successful.
Please suggest me the proper way as the how to subtract the IN time and OUT time and get the TOTAL HOUR as a result only in hours.
You can use Calendar method dateComponents to calculate how many hours there is between two dates. You can use DateFormatter to get the dates from your strings:
let start = "09:35 PM"
let end = "09:36 AM"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "hh:mm a"
if let startDate = dateFormatter.date(from: start),
let endDate = dateFormatter.date(from: end) {
let hours = Calendar.current.dateComponents([.hour], from: startDate, to: endDate < startDate ? Calendar.current.date(byAdding: .day, value: 1, to: endDate) ?? endDate : endDate).hour ?? 0
print(hours) // 12
}
Convert both time into Date object and then just use below statement.
let interval = laterDate.timeIntervalSinceDate(earlierDate)
Hope this will help you...
This question already has answers here:
Checking response Time of API in iOS using Swift 3?
(4 answers)
Closed 3 years ago.
I'm trying to find a way to tell how long its taken a function to execute in seconds. Currently I'm doing it this way:
let startDate = Date()
let endDate = Date()
let calendar = Calendar.current
let dateComponents = calendar.compare(startDate, to: endDate, toGranularity: .second)
let seconds = dateComponents.rawValue
print("Seconds: \(seconds)")
but every time I print out the seconds it always reads -1. I've looked into this question: elapsed time but I need the output to be in seconds. Any suggestions?
Try this:
let start = Date.timeIntervalSinceReferenceDate
// do stuff
let end = Date.timeIntervalSinceReferenceDate
let secondsElapsed = end - start
secondsElapsed will be a Double, but it will be in seconds. You can round it or truncate it if you want an Int.
Hope this helps!
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.
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.
This question already has answers here:
How can I make a countdown timer like in a music player?
(2 answers)
Closed 7 years ago.
I'm trying to make an app that tell us the rest of time from the present time till one hour later.
This is the code but now it only has a function that tell us the countdown time by decreasing one second from the present time.
I'm thinking that I haven't definite the definition of the "cnt"
so that's why I'm thinking it doesn't work.
Can somebody tell me the reason and a solution?
import UIKit
class ViewController: UIViewController {
var cnt : Int = 0
var timer : NSTimer!//NSTimerというデフォルト機能から引っ張る
var myInt:Int = 0
override func viewDidLoad() {
let myDate: NSDate = NSDate()
let myCalendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components([.Year, .Hour, .Minute, .Second],
fromDate: myDate) // myDate、すなわちNSDateから要素として引っ張り出してる
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "onUpdate:", userInfo: nil, repeats: true)//カウントダウンのインターバル
timer.fire()
var myStr: String = "\(myComponents.hour)"
myStr += "\(myComponents.minute)"
myStr += "\(myComponents.second)"
myInt = Int(myStr)! // toInt()がSwift2より無効になったようです。myInt=Str(my components,hour,minute,second)=現時刻
}
func onUpdate(timer : NSTimer){
cnt += 1//cnt+1=cnt,
let count = myInt - cnt //残り時間=現在時刻ー現在時刻に1時間足した時刻
print(count) // println()は、Swift2よりDeprecatedになりました。
}
}
It is difficult to understand what you're asking, but I will do my best.
In your viewDidLoad method, you're setting myInt to the integer representation of myStr. If the time is 18:30:50, myInt will be equal to 183050. That is not an appropriate representation of the time. Time is base 60, integers are base 10, for one thing. If you want to represent time as a single number, you can use timeIntervalSinceDate, or timeIntervalSinceReferenceDate or timeIntervalSince1970 to get the NSTimeInterval (ie. fractional seconds) representation of the date relative to a certain epoch either of your choosing or one built into Foundation.
Subtracting 1 from myInt each time the timer fires isn't going to give you an indication of the time remaining.
Also, NSTimer is not an accurate way to keep time. You should instead save the start date as a property and determine the time remaining based on timeIntervalSinceDate
e.g.
func onUpdate(timer : NSTimer){
let currentTime = NSDate()
let timeElapsed = currentTime.timeIntervalSinceDate(myDate)
println(timeElapsed)
}
If you want to show time elapsed in minutes, you can divide it by 60. You can look into NSDateComponentsFormatter to easily get a string representation of time intervals.
If you want the countdown to stop after an hour, then check for when timeElapsed is over 3600.
If you want it to show a countdown from 1 hour, then subtract the timeElapsed from 3600.