How do I get timestamp interval in swift? - ios

I saw this answer : Get current NSDate in timestamp format
But for some reason it gives me errors.
What I need is to be able to specify the timestamp between now and in the next 2 minutes, or interval between last 2 minutes and now.
Eg: interval => now-2minutes to now (Time between previous 2 minutes and now)
Thank you.

If I got it right, this should clarify things for you:
let calendar = NSCalendar.currentCalendar()
let now = NSDate()
let comps = NSDateComponents()
comps.minute = 2
let twoMinutesFromNow = calendar.dateByAddingComponents(comps, toDate: now, options: NSCalendarOptions.MatchStrictly)
let interval = twoMinutesFromNow?.timeIntervalSinceDate(now)
Here is a nice article about handling NSDates with the use of NSCalendar and NSDateComponents

var curr = NSDate(timeIntervalSince1970: 10000)
var timestep = curr

Related

How to add minutes to custom time in swift2

What I do is:
How to add minutes to current time in swift
how to add 30 minutes to current time
Here is my code:
endFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let endTimeString = "2017-01-16 12:58:56"
let endTime = endFormatter.dateFromString(endTimeString)
endTime?.dateByAddingTimeInterval(180) // 3 Minute
print(endTime)
1st answer #rob i tried that one but failed . second answer suggest dateByAddingTimeInterval i am not suer is it is work or not .
You need to use dateByAddingUnit as #Rob doing instead of dateByAddingTimeInterval. The reason you are not getting correct time is may because of TimeZone so try to set timeZone with your NSDateFormatter instance.
endFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
endFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
let endTimeString = "2017-01-16 12:58:56"
let endTime = endFormatter.dateFromString(endTimeString)
//Now add the 3 minute in endTime
let calendar = NSCalendar.currentCalendar()
let date = calendar.dateByAddingUnit(.Minute, value: 3, toDate: endTime, options: [])
let dateWithMinuteInterval = Calendar.current.date(byAdding: DateComponents(minute: 23), to: endTime)!

Get number of days between two NSDates when crossing new year

I need to get the number of days between two dates which I get but if I input for example: 2016-12-10 and 2017-01-10 there will be a negative number of days. This is just occur when it´s new year between those two dates.
//Get the number of days between two NSDates
func daysBetween(date: NSDate) -> Int {
let calendar: NSCalendar = NSCalendar.currentCalendar()
let date1 = calendar.startOfDayForDate(self)
let date2 = calendar.startOfDayForDate(date)
let components = calendar.components(.Day, fromDate: date1, toDate: date2, options: [])
return components.day
}
//Using the function
let daysBetween = fromDate.daysBetween(toDate)
//Printing -334 if new year is between fromDate and toDate
print(daysBetween)
How can I modify my daysBetween(date: NSDate) function to prevent this from happening?
Edit:
Please don´t pay attention to why it´s printing exacltly -334. That´s just because fromDate and toDate are different days in month. The problem a wanna solve is why the response is negative and not 31 as it should be.
Solved:
It turned out to be as many of you thought. The fromDate is greater then toDate and causing a negative number. Stupid mistake. Thx guys!
You not need to worry about the days going negative. It's better to know if the first date (for example selected from an input UIDatePicker) is bigger than another. That is handled automatically when you converted back to an NSDate.
If the problem is how to print the days , you can use abs(days).
First compare both dates and then you can get correct positive value
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let startDate:NSDate = dateFormatter.dateFromString("2016-12-10")!
let endDate:NSDate = dateFormatter.dateFromString("2017-01-10")!
let cal = NSCalendar.currentCalendar()
let dayUnit: NSCalendarUnit = .Day
if startDate.compare(endDate) == NSComparisonResult.OrderedDescending{
let components = cal.components(dayUnit, fromDate: endDate, toDate: startDate, options: [])
print(components)
} else {
let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: [])
print(components)
}
As Describe by Leo Dabus
You can do it without comparing the dates also:
let com = cal.components(dayUnit, fromDate: startDate.earlierDate(endDate), toDate: startDate.laterDate(endDate), options: [])
print(com)

Get tomorrow's date with Swift 2

I have this code which gives today's date in this formate M/dd/yy
let dateFormater = NSDateFormatter()
dateFormater.dateFormat = "M/dd/yy"
let todayDate = dateFormater.stringFromDate(NSDate())
How can I get the same thing but with next day's date please?
First, you get a NSDate for the day you need, in this example (one day from now is tomorrow):
var oneDayfromNow: Date? {
Calendar.current.date(byAdding: .day, value: 1, to: Date())
}
print(oneDayfromNow)
Then you convert it to your format as string (your case M/dd/yy):
if let oneDayfromNow {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M/dd/yy"
let str = dateFormatter.string(from: oneDayfromNow)
print(str)
}
It's a bit complicated, but it's all things that you need to know anyway.
Why it's difficult: You would think that you could just take NSDate (timeIntervalSinceNow:24 * 60 * 60), adding one day to now. But when you turn on daylight savings time, then 11:30pm plus 24 hours is 00:30am two days later. When daylight savings time is turned off, then 00:30am plus 24 hours can be 11:30pm on the same day.
So you need to create an NSCalendar object, convert NSDate () into components, add one day to the components, convert back to an NSDate (all that gives you the same time on the next day, handling all special cases), and then format the result as you did now.
I finally used this code to fix it :
let dateFormater = NSDateFormatter()
dateFormater.dateFormat = "M/dd/yy"
let todayDate = dateFormater.stringFromDate(NSDate().dateByAddingTimeInterval(24 * 60 * 60))

Neat way to get end of day for date?

I am querying a database for values between a startDate and an endDate. I am therefore looking for a neat way to get the NSDate for the end of the day for a date. Just like you can get startOfDayForDate().
I guess you could do :
let cal = NSCalendar.currentCalendar()
let startOfDay = cal.startOfDayForDate(NSDate())
let aDay:NSTimeInterval = 60*60*23 + 60*59 + 59
let endofDay = startOfDay.dateByAddingTimeInterval(aDay)
Is adding component.day + 1 to startOfDayForDate the correct method to get the "end of the day" for a date, or is there a better method?
A better way would be to get the start of the next day and subtract 0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 second.
Do you get what I want to say? It's very hard to define the end of the day. 23:59 is certainly not the end of the day, there is almost a whole minute left until the next day. And even 23:59:59 is not the end of a day. Because there is an infinite amount of fraction seconds between this time and the start of the next day. As far as I know NSDate supports nanoseconds out of the box, so in the current implementation there are at least 1 000 000 000 possible NSDates between 23:59:59 and the next day.
That's why you should see if you can find a way to use the start of the next day.
For example, instead of if (startOfDay <= date && date <= endOfDay) you could use if (startOfDay <= date && date < startOfNextDay).
To calculate the start of the next day you have to use NSCalendar. In iOS8 Apple added a couple of nice methods to make these calculations short:
let calendar = NSCalendar.currentCalendar()
let startOfDay = calendar.startOfDayForDate(NSDate())
let startOfNextDay = calendar.dateByAddingUnit(.CalendarUnitDay, value: 1, toDate: startOfDay, options: nil)!
EDIT: Since you now state that you want to query a database you don't need to find the end of the day. Check if the date is on or after the start of the day, and before the start of the next day.
Try this:
var endOfDay: Date? {
var components = DateComponents()
components.day = 1
components.second = -1
var calendar = Calendar.current
calendar.timeZone = TimeZone(abbreviation: "GMT")!
return calendar.date(bySettingHour: 11, minute: 59, second: 59, of: Date())
}

To query yesterday records from the Parse table using Swift

I'm going to develop the piece of code to query all the records created yesterday. Well I know it's something very trial. Nevertheless it's one million question for me right now because I'm novice in programming. Below the SWIFT code that doesn't work properly though. For backend I use Parse.com.
var yesterday = NSDate() - 1.day.ago // 1.day.ago isn't valid but what I need.
var query = PFQuery(className:"score") // table name is score
query.whereKey("createdAt", equalTo:"yesterday")
Help please! As always sooner you help higher your chances to win the Tesla Model S Lottery! :)
You can use a pretty cool new attribute of NSCalendar called dateByAddingUnit to easily get yesterday's date:
let today = NSDate()
let yesterday = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay,
value: -1,
toDate: today,
options: NSCalendarOptions(0))
Where you set .CalendarUnitDay as the calendar unit you wish to add/subtract by and the value of -1 to indicate the change you want for that calendar unit.
But the problem with your query is that it specifically requests that a PFObject's "createdAt" date equals a specific time, not that the PFObject was created at anytime during that day. So I suggest you create two constraints in your query -- a greater than and a less than between midnight (the start of the day) yesterday and midnight (the start of the day) today so that the query will return all the results in between.
Update:
To get the start of yesterday and today, i.e. midnight, (converted to GMT to match the dates in the parse database, though that line can be removed if that's not your intent) here's what you can do:
var today = NSDate()
let calendar = NSCalendar.autoupdatingCurrentCalendar()
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let preservedComponents = NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit
today = calendar.dateFromComponents(calendar.components(preservedComponents, fromDate: today))!
var yesterday = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay, value: -1, toDate: today, options: NSCalendarOptions(0))
Then to perform your query:
var query = PFQuery(className:"score") // table name is score
query.whereKey("createdAt", greaterThanOrEqualTo: yesterday)
query.whereKey("createdAt", lessThan: today)
import UIKit
extension NSDate {
func xDays(x:Int) -> NSDate {
return NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: x, toDate: self, options: [])!
}
}
let today = NSDate()
let yesterday = NSDate().xDays(-1)
let dayBeforeYesterday = NSDate().xDays(-2)
Try this:
var yesterday = NSDate.date() - 1.days
var query = PFQuery(className:"score") // table name is score
query.whereKey("createdAt", equalTo:yesterday)
Pay attention at equalTo:yesterday without quotes
Simply try below code. It works fine in iOS7 and iOS8
let today = NSDate()
let tomorrow = today.dateByAddingTimeInterval(24 * 60 * 60)
let yesterday = today.dateByAddingTimeInterval(-24 * 60 * 60)

Resources