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!
Related
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.
This question already has answers here:
NSDate of yesterday
(6 answers)
How to add minutes to current time in swift
(11 answers)
Closed 5 years ago.
I use this code to get the current date
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy.MM.dd"
let result = formatter.string(from: date)
Any idea on how can I get the date in the past, for example a day or a year before the current date?
Try to use this:
Date(timeIntervalSinceNow: -3600); \\One hour
Or you can use Calendar for this
let calendar = Calendar.current
var component = DateComponents()
component.year = -1
calendar.date(byAdding: component, to: Date())
There is a NSTimer object in my app that counts elapsed time in seconds.
I want to format an UILabel in my app's interface in the such way it matches the well know standard.
Example
00:01 - one second
01:00 - 60 seconds
01:50:50 - 6650 seconds
I wonder how to do that, do you know any pods/libraries that creates such String based on Int number of seconds?
Obviously I can come with a complicated method myself, but since it's recommended to not reinvent the wheel, I'd prefer to use some ready-to-use solution.
I haven't found anything relevant in Foundation library, nor in HealthKit
Do you have any suggestions how to get it done? If you say "go and write it yourself" - that's ok. But I wanted to be sure I'm not missing any simple, straightforward solution.
thanks in advance
(NS)DateComponentsFormatter can do that:
func timeStringFor(seconds : Int) -> String
{
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.second, .minute, .hour]
formatter.zeroFormattingBehavior = .pad
let output = formatter.string(from: TimeInterval(seconds))!
return seconds < 3600 ? output.substring(from: output.range(of: ":")!.upperBound) : output
}
print(timeStringFor(seconds:1)) // 00:01
print(timeStringFor(seconds:60)) // 01:00
print(timeStringFor(seconds:6650)) // 1:50:50
Figured it out based on this answer, quite simple!
func createTimeString(seconds: Int)->String
{
var h:Int = seconds / 3600
var m:Int = (seconds/60) % 60
var s:Int = seconds % 60
let a = String(format: "%u:%02u:%02u", h,m,s)
return a
}
This question already has answers here:
How to add minutes to current time in swift
(11 answers)
Closed 7 years ago.
How can I reduce 5 or 10 minutes from current time and then store it as date format in Swift 2.0 ?
let now = NSDate()
var reducedTime = ???? \\ Here I want 10 minutes reduced from current time.
If current time is 02:20:00, then reducedTime should be 02:10:00
How can I do this in a simplest way ???
You can use calendar method dateByAddingUnit and subtract 10 minutes fro the date.
let now = NSDate()
let reducedTime = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)?.dateByAddingUnit(.Minute, value: -10, toDate: now, options: NSCalendarOptions())
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.