Creating a simple countdown to date in Swift 4 - ios

I'm working on a very simple app that counts down to a date. I found several tutorials but nothing in Swift 4. It seems like a lot has changed as I keep getting compiler errors.
Here is my code:
class ViewController: UIViewController {
#IBOutlet weak var CountdownText: UILabel!
let formatter = DateFormatter()
let userCalendar = NSCalendar.current
let requestedComponent: NSCalendar.Unit = [
NSCalendar.Unit.month,
NSCalendar.Unit.day,
NSCalendar.Unit.hour,
NSCalendar.Unit.minute,
NSCalendar.Unit.second,
]
func printTime()
{
formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
let startTime = NSDate()
let endTime = formatter.date(from: "12/03/18 2:00:00 p")
func timeDifference (requestedComponent: NSCalendar.Unit, from: startTime, to: endTime!, options: [NSCalendar.Options]) {}
CountdownText.text = "\(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
}
}
My errors are:
Use of undeclared type 'startTime'
Use of undeclared type 'endTime'

How to use
Copy the Code to your specific View Controller
Change the value of variable dateString with your date in the format
Date Format "< Month > < date >, < year > < hour >:< minute >:< second >"
Ex. "March 4, 2018 13:20:10"
Code
The below code will be useful for achieving a countdown timer of your custom date.
//
// DateCountDownTimer.swift
// CountDownTimerLearning
//
// Created by ThomasVEK on 04/03/18.
// Copyright © 2018 TVEK Solutions. All rights reserved.
//
import Foundation
func defaultUpdateActionHandler(string:String)->(){
}
func defaultCompletionActionHandler()->(){
}
public class DateCountDownTimer{
var countdownTimer: Timer!
var totalTime = 60
var dateString = "March 4, 2018 13:20:10" as String
var UpdateActionHandler:(String)->() = defaultUpdateActionHandler
var CompletionActionHandler:()->() = defaultCompletionActionHandler
public init(){
countdownTimer = Timer()
totalTime = 60
dateString = "March 4, 2018 13:20:10" as String
UpdateActionHandler = defaultUpdateActionHandler
CompletionActionHandler = defaultCompletionActionHandler
}
public func initializeTimer(pYear:Int, pMonth:String, pDay:Int, pHour:Int, pMin:Int, pSec:Int){
self.dateString = "\(pMonth) \(pDay), \(pYear) \(pHour):\(pMin):\(pSec)" as String
// Setting Today's Date
let currentDate = Date()
// Setting TargetDate
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss"
dateFormatter.timeZone = NSTimeZone.local
let targedDate = dateFormatter.date(from: dateString) as! Date
// Calculating the difference of dates for timer
let calendar = Calendar.current.dateComponents([.day, .hour, .minute, .second], from: currentDate, to: targedDate)
let days = calendar.day!
let hours = calendar.hour!
let minutes = calendar.minute!
let seconds = calendar.second!
totalTime = hours * 60 * 60 + minutes * 60 + seconds
totalTime = days * 60 * 60 * 24 + totalTime
}
func numberOfDaysInMonth(month:Int) -> Int{
let dateComponents = DateComponents(year: 2015, month: 7)
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)!
let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count
print(numDays)
return numDays
}
public func startTimer(pUpdateActionHandler:#escaping (String)->(),pCompletionActionHandler:#escaping ()->()) {
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
self.CompletionActionHandler = pCompletionActionHandler
self.UpdateActionHandler = pUpdateActionHandler
}
#objc func updateTime() {
self.UpdateActionHandler(timeFormatted(totalTime))
if totalTime > 0 {
totalTime -= 1
} else {
endTimer()
}
}
func endTimer() {
self.CompletionActionHandler()
countdownTimer.invalidate()
}
func timeFormatted(_ totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
let minutes: Int = (totalSeconds / 60) % 60
let hours: Int = (totalSeconds / 60 / 60) % 24
let days: Int = (totalSeconds / 60 / 60 / 24)
return String(format: "%dD %02dH %02dM %02dS", days, hours, minutes, seconds)
}
}

You have specified timeDifference function inside printTime() function and in timeDifference() function you have defined from and to parameters which ones types are startTime and endTime which ones are not types. Replace them with NSDate like:
func timeDifference (requestedComponent: NSCalendar.Unit, from: NSDate, to: NSDate, options: [NSCalendar.Options]) {}
and then call this function with startTime and ednTime variables that you have defined.
Also I think that you should define timeDifference function outside of printTime function.

Related

Number of days between two timestamps

I want to get number of days between two timestamps but I am getting wrong value using this code.
Code :
let currentDateTimeStamp = Date().timeIntervalSince1970 * 1000.0
let firstDate = Date.init(timeIntervalSince1970: currentDateTimeStamp)
let lastDate = Date.init(timeIntervalSince1970: individualCellData["joining_date"] as! TimeInterval)
// First Method using extension
let daysBetween = firstDate.interval(ofComponent: .day, fromDate: lastDate)
// Second method
let components = Calendar.current.dateComponents([.day], from: lastDate, to: firstDate)
extension Date {
func interval(ofComponent comp: Calendar.Component, fromDate date: Date) -> Int {
let currentCalendar = Calendar.current
guard let start = currentCalendar.ordinality(of: comp, in: .era, for: date) else { return 0 }
guard let end = currentCalendar.ordinality(of: comp, in: .era, for: self) else { return 0 }
return end - start
}
}
I am getting timestamp from server in milliseconds. What is the correct way ?
let date1 = NSDate(timeIntervalSince1970: 1507211263)//Thursday, 5 October 2017 13:47:43
let date2 = NSDate(timeIntervalSince1970: 1507556863)//Monday, 9 October 2017 13:47:43
var secondsBetween: TimeInterval = date2.timeIntervalSince(date1 as Date)
var numberOfDays = Int(secondsBetween / 86400)
print("There are \(numberOfDays) days in between the two dates.")
//FYI: 86400 seconds = 24 hr
extension Date {
func timeStampToDay(timeStampInMillisecond:Double) -> Int {
let date = Date()
let todaysDateStamp = date.timeIntervalSince1970
let timeStampDate = Date(timeIntervalSince1970: timeStampInMillisecond / 1000)
var secBetween = Date(timeIntervalSince1970: todaysDateStamp).timeIntervalSince(timeStampDate)
return Int(abs(secBetween) / 86400)
}
func timeStampToDay(timeStampInSecond:Double) -> Int {
let date = Date()
let todaysDateStamp = date.timeIntervalSince1970
let timeStampDate = Date(timeIntervalSince1970: timeStampInMillisecond)
var secBetween = Date(timeIntervalSince1970: todaysDateStamp).timeIntervalSince(timeStampDate)
return Int(abs(secBetween) / 86400)
}
}

How to get week start date and end date by using any Month and week number swift 3?

I have to implement graph so that I need to get week start date and weekend date if I will pass the date object and week number.
How can I achieve that I tried it but didn't get exactly?
Here below is my code:-
Weekday:-
//Day of week
func getDayOfWeek(today:String)->Int? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
if let todayDate = formatter.date(from: today) {
let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
let myComponents = myCalendar.components(.weekday, from: todayDate)
let weekDay = myComponents.weekday
return weekDay
} else {
return nil
}
}.
extension Date {
var millisecondsSince1970:Int {
return Int((self.timeIntervalSince1970 * 1000.0).rounded())
}
init(milliseconds:Int) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
}
func startOfWeek(weekday: Int?) -> Date {
var cal = Calendar.current
var component = cal.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
component.to12am()
cal.firstWeekday = weekday ?? 1
return cal.date(from: component)!
}
func endOfWeek(weekday: Int) -> Date {
let cal = Calendar.current
var component = DateComponents()
component.weekOfYear = 1
component.day = -1
component.to12pm()
return cal.date(byAdding: component, to: startOfWeek(weekday: weekday))!
}
}
internal extension DateComponents {
mutating func to12am() {
self.hour = 0
self.minute = 0
self.second = 0
}
mutating func to12pm(){
self.hour = 23
self.minute = 59
self.second = 59
}
}
This returns start- and end date for a given week number and date
func dayRangeOf(weekOfYear: Int, for date: Date) -> Range<Date>
{
let calendar = Calendar.current
let year = calendar.component(.yearForWeekOfYear, from: date)
let startComponents = DateComponents(weekOfYear: weekOfYear, yearForWeekOfYear: year)
let startDate = calendar.date(from: startComponents)!
let endComponents = DateComponents(day:7, second: -1)
let endDate = calendar.date(byAdding: endComponents, to: startDate)!
return startDate..<endDate
}
print(dayRangeOf(weekOfYear: 12, for: Date()))
Consider that print displays the dates in UTC and the start date depends on the first weekday setting of the current locale.
Edit
A version to determine the range of a given week of month
func dayRangeOf(weekOfMonth: Int, year: Int, month: Int) -> Range<Date>? {
let calendar = Calendar.current
guard let startOfMonth = calendar.date(from: DateComponents(year:year, month:month)) else { return nil }
var startDate = Date()
if weekOfMonth == 1 {
var interval = TimeInterval()
guard calendar.dateInterval(of: .weekOfMonth, start: &startDate, interval: &interval, for: startOfMonth) else { return nil }
} else {
let nextComponents = DateComponents(year: year, month: month, weekOfMonth: weekOfMonth)
guard let weekStartDate = calendar.nextDate(after: startOfMonth, matching: nextComponents, matchingPolicy: .nextTime) else {
return nil
}
startDate = weekStartDate
}
let endComponents = DateComponents(day:7, second: -1)
let endDate = calendar.date(byAdding: endComponents, to: startDate)!
return startDate..<endDate
}
print(dayRangeOf(weekOfMonth: 5, year: 2017, month: 6))
The result type of the second version is an optional because there are a few calculations which could fail for example if the number of week in the particular month is out of range.
For anyone interested in this, it looks like OP confusing weekOfMonth and weekOfYear…
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
let cal = Calendar.current
let dateComponents = DateComponents(year: 2018, month: 3, day: 15)
let date = cal.date(from: dateComponents)!
func weekOfMonthStart(forDate date: Date) -> Date {
var compsToWeekOfMonth = cal.dateComponents([.year, .month, .weekOfYear], from: date)
compsToWeekOfMonth.day = cal.range(of: .day, in: .weekOfMonth, for: date)?.lowerBound
return cal.date(from: compsToWeekOfMonth)!
}
Somebody mention an answer that will fail, so a test was included ;)
for i in 0...5000 {
let newDate = cal.date(byAdding: DateComponents(day:i), to: date)!
weekOfMonthStart(forDate: newDate)
}

How to make 30 minute time intervals in swift 2.3

startTime = 10:00 AM
endTime = 01:00 PM
Now i want to split the time in the interval of 30mins like
10:00 AM 10:30 AM 11:00 AM 11:30 AM .......... till 01:00 PM.
I tried like
let startDate : NSDate! = NSDate()
let time1 : NSDate = startDate.dateByAddingTimeInterval((60*60)/2)
let time2 : NSDate = time1.dateByAddingTimeInterval((60*60)/2)
let time3 : NSDate = time2.dateByAddingTimeInterval((60*60)/2)
let time4 : NSDate = time3.dateByAddingTimeInterval((60*60)/2)
func makeTimeInterval(startTime:String ,endTime:String) -> String
{
let timeFormat = DateFormatter()
timeFormat.dateFormat = "hh:mm a"
var fromTime:NSDate = (timeFormat.date(from:startTime) as NSDate?)!
let toTime:NSDate = (timeFormat.date(from:endTime) as NSDate?)!
var dateByAddingThirtyMinute : NSDate!
let timeinterval : TimeInterval = toTime.timeIntervalSince(fromTime as Date)
let numberOfIntervals : Double = timeinterval / 3600;
var formattedDateString : String!
for _ in stride(from: 0, to: Int(numberOfIntervals * 2), by: 1)
{
dateByAddingThirtyMinute = fromTime.addingTimeInterval(1800)
fromTime = dateByAddingThirtyMinute
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
formattedDateString = dateFormatter.string(from: dateByAddingThirtyMinute! as Date) as String?
print("Time after 30 min = \(formattedDateString)")
}
return formattedDateString
}
Tried those things and i got like 10:10,10:40..etc
how to make 30 min round of interval like 10:00,10:30...etc
Thanks in advance
Use the below function if user enters anytime less than 30 than it will start with very next 30 min e.g 10:20, start from 10:30. And if user give time greater than 30 then very time will be 00 e.g 10:45, start from 11:00.
func makeTimeInterval(startTime:String ,endTime:String) -> String
{
var arr = startTime.components(separatedBy: " ")[0].components(separatedBy: ":")
let str = arr[1] as String
if (Int(str)! > 0 && Int(str)! < 30){
arr[1] = "00"
}
else if(Int(str)! > 30){
arr[1] = "30"
}
let startT:String = "\(arr.joined(separator: ":")) \(startTime.components(separatedBy: " ")[1])"
let timeFormat = DateFormatter()
timeFormat.dateFormat = "hh:mm a"
var fromTime:NSDate = (timeFormat.date(from:startT) as NSDate?)!
let toTime:NSDate = (timeFormat.date(from:endTime) as NSDate?)!
var dateByAddingThirtyMinute : NSDate!
let timeinterval : TimeInterval = toTime.timeIntervalSince(fromTime as Date)
let numberOfIntervals : Double = timeinterval / 3600;
var formattedDateString : String!
for _ in stride(from: 0, to: Int(numberOfIntervals * 2), by: 1)
{
dateByAddingThirtyMinute = fromTime.addingTimeInterval(1800)
fromTime = dateByAddingThirtyMinute
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
formattedDateString = dateFormatter.string(from: dateByAddingThirtyMinute! as Date) as String?
print("Time after 30 min = \(formattedDateString)")
}
return formattedDateString
}
You can user Calendar Components to set minutes 00 and then calculate intervals:
func getIntervals(start: String, end: String)->[Date]{
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
var fromDate = formatter.date(from: start)!
let calendar = Calendar(identifier: .gregorian)
let component = calendar.dateComponents([.hour, .minute], from: fromDate)
fromDate = calendar.date(bySettingHour: component.hour!, minute: 0, second: 0, of: fromDate)!
let thirtyMin: TimeInterval = 1800
let endDate = formatter.date(from: end)!
var intervals = Int(endDate.timeIntervalSince(fromDate)/thirtyMin)
intervals = intervals < 0 ? 0 : intervals
var dates = [Date]()
for x in 0...intervals{
let date = fromDate.addingTimeInterval(TimeInterval(x)*thirtyMin)
dates.append(date)
}
return dates
}
let timeIntervals = getIntervals(start: "10:10 am", end: "1:40 pm")
You can use NSDateComponents class. This class allow to get some date units. You can get minutes and hours values from the date and round the minutes to nearest "good" value (sometimes you should be change hours also).
After that you can get new date with new values of hours and minutes.
Don't forget about a time zone.
NSDate* date = [NSDate date]; //start date
NSCalendar* calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents* components = [calendar components:(NSCalendarUnitMinute | NSCalendarUnitHour) fromDate:date];
NSInteger minutes = [components minute];
NSInteger hours = [components hour];
NSInteger nearestGoodMinutes = [self _nearestGoodMinutesForMinutes:minutes];
BOOL shouldIncHours = [self _shouldINcHoursForMinutes:minutes];
if (shouldIncHours)
{
hours++;
}
NSDate* dateWithGoodHours = [calendar dateBySettingUnit:NSCalendarUnitHour value:hours ofDate:date options:kNilOptions];
NSDate* goodDate = [calendar dateBySettingUnit:NSCalendarUnitMinute value:nearestGoodMinutes ofDate:dateWithGoodHours options:kNilOptions];
Some explanation. NSDate does not contain any date components. Date components depend on current callendar. Also values of the components depent on current time zone. If you create NSCalendar with identifier, you will get calendar in current time zone. The time zone should be same with time zone that you use for displaying of the date to the user.
P.S.
You can do it only for the start date.
func format(minute: Int) {
let h = minute / 60
let m = minute % 60
timeLabel.text = "\(h.padZero()):\(m.padZero())"
}
private extension Int {
func padZero() -> String {
return String(format: "%02d", self)
}
}
Refered to this post https://github.com/onmyway133/blog/issues/340

I'm trying to have my app pop viewControllers when it reaches 9:00 UTC time every day

I'm trying have my app pop viewControllers when it reaches 9:00 UTC time every day. I don't want it to use local time as that can change in different regions, and can be altered. I thought of using a server time, but I'm having issues getting that solution to work. I got an epoch timestamp and converted it to a Date.
let ref = FIRDatabase.database().reference()
let timestamp = FIRServerValue.timestamp()
ref.setValue(timestamp)
ref.observe(.value, with: {
snap in
if let t = snap.value as? TimeInterval {
// Cast the value to an NSTimeInterval
// and divide by 1000 to get seconds.
print("this is the time in seconds \(t)")
let date = Date(timeIntervalSince1970: t)
print("this is the time \(Date(timeIntervalSince1970: t/1000))")
It prints out this is the time 2016-10-10 18:40:21 +0000.
The problem is figuring out how to get only the hour minutes and seconds out of this so I can compare the time dates.
One of options might be:
To request a current time from the server on the start of the app.
Calculate a difference between 9:00 UTC and the current time.
Set a timer (NSTimer) which fires when the difference has passed.
And finally, handle the callback in any way you like: pop screens, show a popup, etc.
You could use something like this:
let calendar = Calendar.current
let components = NSDateComponents()
components.hour = 9
let nineOClock = calendar.nextDate(after: Date(), matching: components as DateComponents, matchingPolicy: .strict)
let timer = Timer(fireAt: nineOClock!, interval: 0, target: self, selector: #selector(doSomething), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
func doSomething(){
print("Doing something")
}
A method which calculates time (in seconds) until the next 9 am based on the current time (seconds from 1970).
func untilNineAmSeconds(now: Int) -> Int {
let todaySeconds = now % 86400
let hourSeconds = 3600
let nineAmSeconds = 9 * hourSeconds
let daySeconds = 24 * hourSeconds
if todaySeconds < nineAmSeconds {
return nineAmSeconds - todaySeconds
} else {
return (daySeconds - todaySeconds) + nineAmSeconds
}
}
Now you (1) request a current time from Firebase, (2) get a time interval before 9 am, and (3) schedule a timer.
let ref = FIRDatabase.database().reference()
let timestamp = FIRServerValue.timestamp()
ref.setValue(timestamp)
ref.observe(.value, with: { snap in
guard let ts = snap.value as? TimeInterval else {
return
}
let seconds = untilNineAmSeconds(now: Int(ts))
let timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(seconds), repeats: false) { _ in
// TODO: pop view controllers
}
// ...
}
Thanks to Artem and his help, I was directed on the right path. After a lot of time spent researching date conversion, I figured this out. The final goal is to convert the two values into Integers so I can compare them in seconds and use them in a timer to figure out how much time is remaining.
ref.observe(.value, with: {
snap in
if let t = snap.value as? TimeInterval {
let FinalTimeInterval = self.convertStringToDateToIntStartTime() - self.convertEpochTimeStampToDateToStringToDateToIntEndTime(timeInterval: t)
if FinalTimeInterval < 0 {
print("less than zero")
} else {
let timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(FinalTimeInterval), repeats: false) { _ in
// TODO: pop view controllers
print("i'm so happy this is working")
}
RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
}
}
})
func convertEpochTimeStampToDateToStringToDateToIntEndTime(timeInterval: TimeInterval) -> Int {
let date = Date(timeIntervalSince1970: timeInterval/1000)
var dateFormater = DateFormatter()
dateFormater.timeZone = TimeZone(identifier: "UTC")
dateFormater.dateFormat = "HH:mm:ss"
let dateString = dateFormater.string(from: date)
let endTime = dateFormater.date(from: dateString)
dateFormater.dateFormat = "HH"
let endHours = Int(dateFormater.string(from: endTime!))
dateFormater.dateFormat = "mm"
let endMinutes = Int(dateFormater.string(from: endTime!))
dateFormater.dateFormat = "ss"
let endSeconds = Int(dateFormater.string(from: endTime!))
return endSeconds! + endMinutes! * 60 + endHours! * 3600
}
func convertStringToDateToIntStartTime() -> Int {
var dateFormater = DateFormatter()
dateFormater.timeZone = TimeZone(identifier: "UTC")
dateFormater.dateFormat = "HH:mm:ss"
let startTime = dateFormater.date(from: "09:00:00")
dateFormater.dateFormat = "HH"
let startHours = Int(dateFormater.string(from: startTime!))
dateFormater.dateFormat = "mm"
let startMinutes = Int(dateFormater.string(from: startTime!))
dateFormater.dateFormat = "ss"
let startSeconds = Int(dateFormater.string(from: startTime!))
return startSeconds! + startMinutes! * 60 + startHours! * 3600
}

How to add minutes to current time in swift

I am new to Swift and am trying a scheduler. I have the start time selected and I need to add 5 minutes (or multiples of it) to the start time and display it in an UILabel?
#IBAction func timePickerClicked(sender: UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var dateStr = dateFormatter.stringFromDate(startTime.date)
let sttime = dateStr
startTimeDisplay.text = dateStr
}
// How to advance time by 5 minutes for each section based on the start time selected and display time
// section 1 = start time + 5
// section 2 = start time + 10*
Two approaches:
Use Calendar and date(byAdding:to:wrappingComponents:). E.g., in Swift 3 and later:
let calendar = Calendar.current
let date = calendar.date(byAdding: .minute, value: 5, to: startDate)
Just use + operator (see +(_:_:)) to add a TimeInterval (i.e. a certain number of seconds). E.g. to add five minutes, you can:
let date = startDate + 5 * 60
(Note, the order is specific here: The date on the left side of the + and the seconds on the right side.)
You can also use addingTimeInterval, if you’d prefer:
let date = startDate.addingTimeInterval(5 * 60)
Bottom line, +/addingTimeInterval is easiest for simple scenarios, but if you ever want to add larger units (e.g., days, months, etc.), you would likely want to use the calendrical calculations because those adjust for daylight savings, whereas addingTimeInterval doesn’t.
For Swift 2 renditions, see the previous revision of this answer.
You can use Calendar's method
func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?
to add any Calendar.Component to any Date. You can create a Date extension to add x minutes to your UIDatePicker's date:
Xcode 8 and Xcode 9 • Swift 3.0 and Swift 4.0
extension Date {
func adding(minutes: Int) -> Date {
return Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
}
}
Then you can just use the extension method to add minutes to the sender (UIDatePicker):
let section1 = sender.date.adding(minutes: 5)
let section2 = sender.date.adding(minutes: 10)
Playground testing:
Date().adding(minutes: 10) // "Jun 14, 2016, 5:31 PM"
Swift 4:
// add 5 minutes to date
let date = startDate.addingTimeInterval(TimeInterval(5.0 * 60.0))
// subtract 5 minutes from date
let date = startDate.addingTimeInterval(TimeInterval(-5.0 * 60.0))
Swift 5.1:
// subtract 5 minutes from date
transportationFromDate.addTimeInterval(TimeInterval(-5.0 * 60.0))
extension Date {
func withAddedMinutes(minutes: Double) -> Date {
addingTimeInterval(minutes * 60)
}
func withAddedHours(hours: Double) -> Date {
withAddedMinutes(minutes: hours * 60)
}
}
useCase
let anHourFromNow = Date().withAddedHours(hours: 1)
let aMinuteFromNow = Date().withAddedMinutes(minutes: 1)
You can use in swift 4 or 5
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
let current_date_time = dateFormatter.string(from: date)
print("before add time-->",current_date_time)
//adding 5 miniuts
let addminutes = date.addingTimeInterval(5*60)
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
let after_add_time = dateFormatter.string(from: addminutes)
print("after add time-->",after_add_time)
output:
before add time--> 2020-02-18 10:38:15
after add time--> 2020-02-18 10:43:15
You can do date arithmetic by using NSDateComponents. For example:
import Foundation
let comps = NSDateComponents()
comps.minute = 5
let cal = NSCalendar.currentCalendar()
let r = cal.dateByAddingComponents(comps, toDate: NSDate(), options: nil)
It is what you see when you try it in playground
NSDate.init with timeIntervalSinceNow:
Ex:
let dateAfterMin = NSDate.init(timeIntervalSinceNow: (minutes * 60.0))
Save this little extension:
extension Int {
var seconds: Int {
return self
}
var minutes: Int {
return self.seconds * 60
}
var hours: Int {
return self.minutes * 60
}
var days: Int {
return self.hours * 24
}
var weeks: Int {
return self.days * 7
}
var months: Int {
return self.weeks * 4
}
var years: Int {
return self.months * 12
}
}
Then use it intuitively like:
let threeDaysLater = TimeInterval(3.days)
date.addingTimeInterval(threeDaysLater)
Swift 3:
let minutes: TimeInterval = 1 * 60
let nowPlusOne = Date() + minutes
I think the simplest will be
let minutes = Date(timeIntervalSinceNow:(minutes * 60.0))
In case you want unix timestamp
let now : Date = Date()
let currentCalendar : NSCalendar = Calendar.current as NSCalendar
let nowPlusAddTime : Date = currentCalendar.date(byAdding: .second, value: accessTime, to: now, options: .matchNextTime)!
let unixTime = nowPlusAddTime.timeIntervalSince1970

Resources