where is timeIntervalSince1970 property in swift - ios

I am trying to get the current milliseconds and according to all the questions on Google, i should use timeIntervalSince1970 property of NSDate
however i already did this:
var startTime = NSData()
and then
startTime. timeIntervalSince1970
and
startTime. timeIntervalSince1970()
but it seems there is no property anymore, right?
if yes, what is the replacement please?

The error is: NSDate not NSData.
Also there should not be space after the "."?
var startTime = NSDate()
let interval = startTime.timeIntervalSince1970
From Apple docs:
var timeIntervalSince1970: NSTimeInterval { get }
This property’s value is negative if the date object is earlier than January 1, 1970 at 12:00 a.m. GMT.

Related

iOS Core Motion how to convert timestamp to Date?

I'm examining CMRecordedAccelerometerData and it has a timestamp, defined as:
The timestamp is the amount of time in seconds since the device
booted.
How do I convert timestamp from device last boot to NSDate?
For example, the system provides a CMRecordedAccelerometerData object with a timestamp value of: 1030958.895134
If I use any of the available reference frames (1970, reference date), I will get a wrong date, not in 2019. I want the real date when the event was recorded.
This answer comes a bit late I guess, but, first, you can get the boot time by subtracting the uptime ProcessInfo.processInfo.systemUptime from now, but otherwise from iOS 9+ ProcessInfo.processInfo.systemUptime has the date property startDate, which should be what you were after in the first place.
The timestamp is a TimeInterval, a typealias for Double that represents duration as a number of seconds. So you can convert TimeInterval to a Date by using NSDate's (timeIntervalSince1970:).
let myTimeInterval:TimeInterval = 1574660642
let dateNow = NSDate(timeIntervalSince1970: myTimeInterval) //will print "Nov 24, 2019 at 9:44 PM"
If you need to the date relative to the current date with the TimeInterval, you can use (timeInterval:since:).
var date = Date()
let timestampOfLastBoot: TimeInterval = 1572628813
let currentTimestamp: TimeInterval = NSDate().timeIntervalSince1970
let dateOfTimeStamp = Date(timeInterval: timestampOfLastBoot-currentTimestamp, since: date) //will print "Nov 1, 2019 at 10:20 AM"

ios Swift - trouble setting time with seconds at zero [duplicate]

I have a date picker that returns me a NSdate value. And I want to have a date value of seconds set to 0. I have the code to do it in objective c as
NSTimeInterval time = floor([date timeIntervalSinceReferenceDate] / 60.0) * 60.0;
return [NSDate dateWithTimeIntervalSinceReferenceDate:time];
where date is the datepicker's date. So how to realise this in swift?
It is almost identical in Swift:
let date = NSDate()
let ti = floor(date.timeIntervalSinceReferenceDate/60.0) * 60.0
let date1 = NSDate(timeIntervalSinceReferenceDate: ti)
The same can be achieved with NSCalendar methods:
let cal = NSCalendar.currentCalendar()
var date2 : NSDate?
cal.rangeOfUnit(.Minute, startDate: &date2, interval: nil, forDate: date)
and this has the great advantage that it can easily be adapted for
larger time units like days, months, etc. which do not have a fixed
length (e.g. a day can have 23, 24, or 25 hours in regions with
daylight saving time).

Swift - How to check if an NSDate is yesterday compare to current time?

I have an NSDate value. I need to check (compare to system current time) if that is yesterday or not. I thought that was easy because I could just pull the day value out of my NSDate and +1 to compare it. But soon afterward, I realized it's an inappropriate idea because what if it's end of the month, let's say July 31. And next day is not July 32, is August 1.
What's the most effective way to check if an NSDate is yesterday (compare to current time)?
As of iOS 8.0, you can use -[NSCalendar isDateInYesterday:], like this:
let calendar = NSCalendar.autoupdatingCurrentCalendar()
let someDate: NSDate = some date...
if calendar.isDateInYesterday(someDate) {
// It was yesterday...
}
If you'll be doing this a lot, you should create the calendar once and keep it in an instance variable, because creating the calendar object is not trivial.
In Swift 3/4/5 the API has changed:
Calendar.current.isDateInToday(yourDate)
Calendar.current.isDateInYesterday(yourDate)
Calendar.current.isDateInTomorrow(yourDate)
To get the current date:
let now = Date()
Here is an extension in Swift to check if the date is past date.
extension Date {
var isPastDate: Bool {
return self < Date()
}
func isYesterday() -> Bool {
return Calendar.current.isDateInYesterday(self)
}
}
Usage:
let someDate = Date().addingTimeInterval(1)
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
print(date.isPastDate)
}

How would I be able to convert the date into an integer?

I need to be able to convert the date of the day to an integer so that I can then save it as an integer to use in other areas in my code. I know that there are other ways to save a date in Xcode, but for this specific problem I need to use it as an integer. So my over all question is how would I be able to convert the date into an integer so that I can then use that integer in an NSString? Thanks in advance!
You can do that by using the timeIntervalSinceReferenceDate method.
// Get time from baseline date to now as a double.
double interval = [[NSDate date] timeIntervalSinceReferenceDate];
// Re-apply the time value
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:interval];
Reference date is a base line date that will always have the same value. So you can safely use it as a reference point. Then you just store the NSTimeInterval (typedef to double) between the reference date and now. That gives you the number of seconds that has taken place between the reference date and now.
Edit:
As mentioned in the comments, if your date is eArlier than 2001, you can use the 1970 reference date.
// Get time from baseline date to now as a double.
double interval = [[NSDate date] timeIntervalSince1970];
// Re-apply the time value
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
If your dates are later than 2001, either method will work for you.
You may convert from double to integer using
int interval = (int)[[NSDate date] timeIntervalSince1970];
Since the double will be truncated to the nearest second, you will want to decide if you want to round up or down. Leaving as is will round down. You can round to the proper nearest second by using:
interval = round(interval);

NSDate - Convert Date to GMT

I need the ability to convert an NSDate value to a GMT Date.
How can I go about converting an NSDate value to a GMT formatted NSDate value, independent of whatever date locale settings the iPhone device is using?
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm";
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];
Working with time in Cocoa can be complicated. When you get an NSDate object, it's in the local time zone. [[NSTimeZone defaultTimeZone] secondsFromGMT] gives you the offset of the current time zone from GMT. Then you can do this:
NSDate *localDate = // get the date
NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method
NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];
Now gmtDate should have the correct date in GMT for you. In order to display it, look at NSDateFormatter, specifically the setDateStyle and setTimeStyle methods. You create an NSDateFormatter, configure it the way you want, and then call stringFromDate: to get a nicely formatted string.
Howard's Answer is correct and please vote it up and accept it.
For reference I think it is useful to explain the difference between date objects and localised date representations are.
In many programming languages date objects are used to represent unique points in time. Ignoring Relativistic arguments it can be assumed that at any instance we can define a point in time which is equal universally for every one, regardless of how we measure time.
If for each point in time we could construct a unique label, that label could be passed around and referenced unambiguously. The purpose of date objects is to act as a unique universal label for a given point in time.
One could come up with any number of techniques to construct such a labelling scheme and how each date object chooses to do so is immaterial to anyone using them.
An example may be to use a numeric offset from a universal event (X seconds since the sun exploded).
It is only when we wish to take a time point and serialize it into a human readable string that we must deal with the complexities of time zones, locales, etc...
(Local Date String) + (Date Formatter) => Time Point
Time Point + (Date Formatter) => (Local Date String)
Every time point is universal... there is no such thing as a new york time point, or gmt time point, only once you convert a time point to a local string (using a date formatter) does any association to a time zone appear.
Note: I'm sure there are many blogs/articles on this very issue, but my google foo is failing me at this hour. If anyone has the enthusiasm to expand on this issue please feel free to do so.
Swift 4:
//UTC or GMT ⟺ Local
extension Date {
// Convert local time to UTC (or GMT)
func toGlobalTime() -> Date {
let timezone = TimeZone.current
let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
}
While Alex's answer was a good start, it didn't deal with DST (daylight savings time) and added an unnecessary conversion to/from the reference date. The following works for me:
To convert from a localDate to GMT, taking DST into account:
NSDate *localDate = <<your local date>>
NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:localDate];
NSDate *gmtDate = [localDate dateByAddingTimeInterval:-timeZoneOffset]; // NOTE the "-" sign!
To convert from a GMT date to a localDate, taking DST into account:
NSDate *gmtDate = <<your gmt date>>
NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:gmtDate];
NSDate *localDate = [gmtDate dateByAddingTimeInterval:timeZoneOffset];
One small note: I used dateByAddingTimeInterval, which is iOS 4 only. If you are on OS 3 or earlier, use addTimerInterval.
Have you tried looking at the documentation for NSDateFormatter?
NSDateFormatter
NSDateFormatter appears to have some methods for playing with TimeZones, particularly
-setTimeZone:
I haven't tested it myself, but I imagine that if you set GMT as the timezone on a date that is originally represented in another timezone, it will display the date with the correct adjustments to match the new timezone.

Resources