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

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);

Related

where is timeIntervalSince1970 property in swift

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.

How to compare two dates in iOS [duplicate]

This question already has answers here:
iOS: Compare two dates
(6 answers)
Closed 9 years ago.
I want to compare two dates.This my code i wrote
NSDate *c_date=[NSDate date];
NSDate *newDate = [c_date dateByAddingTimeInterval:300];
This code is not working?What i am missing?
From NSDate, you can use
- (NSComparisonResult)compare:(NSDate *)anotherDate
You can use
- (NSComparisonResult)compare:(NSDate *)other;
which will yield a
typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};
in your example you're just creating two different NSDate objects with a known NSTimeInterval (300), so there is no comparison.
Use [NSDate timeIntervalSince1970] which will return a simple double value that can be used for comparison just like any other.
NSDate *c_date=[NSDate date];
NSDate *newDate = [c_date dateByAddingTimeInterval:300];
NSTimeInterval c_ti = [c_date timeIntervalSince1970];
NSTimeInterval new_ti = [newDate timeIntervalSince1970];
if (c_ti < new_ti) {
// c_date is before newDate
} else if (c_ti > new_ti) {
// c_date is after newDate
} else {
// c_date and newDate are the same
}
There are also the [NSDate compare:] method, that you might find more convenient.
Here's the thing (well, it might be the thing, it's not completely 100% clear from your question). NSDate represents an interval in seconds since 1st January 1970. Internally, it uses a floating point number (a double in OS X, not sure in iOS). This means that comparing two NSDates for equality is dry hit and miss, actually it's mostly miss.
If you want to make sure one date is within, say, 1/2 a second of another date, try:
fabs([firstDate timeIntervalSinceDate: secondDate]) < 0.5
If you just want both dates to be on the same day, you'll need to muck about with NSCalendar and date components.
See also this SO answer.
https://stackoverflow.com/a/6112384/169346

ios minutes to time

I want to go from minutes as an int (eg 92) to a string of 1:32. Is there a fancy way to do this using objc or I'm I stuck with figuring it out the old-fashioned way?
I do not believe there is a function to do this, but it is simple enough to do on your own.
int hour = minutes / 60;
int min = minutes % 60;
NSString *timeString = [NSString stringWithFormat: %#"%d:%02d", hour, min];
The '02' will pad the results so there are always two digits in the minutes place. It may be useful to look at the NSDate Class Reference as it may save you time if you want to do calculations on the result.
I think you can find the answer here: NSTimeInterval to NSDate
The int you talking about should be NSTimeInterval (that is just double), convert it to a NSDate object and then format it using the NSDateFormatter with: HH:mm.
It can also could be more useful "extend" using categories NSDate object
#interface NSDate (Minutes)
and put there a method convert minutes to HH:mm (maybe could be better to move the format string as method parameter) so you never more need think about it.

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.

iPhone: How to get current milliseconds?

What is the best way to get the current system time milliseconds?
If you're looking at using this for relative timing (for example for games or animation) I'd rather use CACurrentMediaTime()
double CurrentTime = CACurrentMediaTime();
Which is the recommended way; NSDate draws from the networked synch-clock and will occasionally hiccup when re-synching it against the network.
It returns the current absolute time, in seconds.
If you want only the decimal part (often used when syncing animations),
let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)
[[NSDate date] timeIntervalSince1970];
It returns the number of seconds since epoch as a double. I'm almost sure you can access the milliseconds from the fractional part.
I benchmarked all the other answers on an iPhone 4S and iPad 3 (release builds). CACurrentMediaTime has the least overhead by a small margin. timeIntervalSince1970 is far slower than the others, probably due to NSDate instantiation overhead, though it may not matter for many use cases.
I'd recommend CACurrentMediaTime if you want the least overhead and don't mind adding the Quartz Framework dependency. Or gettimeofday if portability is a priority for you.
iPhone 4S
CACurrentMediaTime: 1.33 µs/call
gettimeofday: 1.38 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.45 µs/call
CFAbsoluteTimeGetCurrent: 1.48 µs/call
[[NSDate date] timeIntervalSince1970]: 4.93 µs/call
iPad 3
CACurrentMediaTime: 1.25 µs/call
gettimeofday: 1.33 µs/call
CFAbsoluteTimeGetCurrent: 1.34 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.37 µs/call
[[NSDate date] timeIntervalSince1970]: 3.47 µs/call
In Swift we can make a function and do as follows
func getCurrentMillis()->Int64{
return Int64(NSDate().timeIntervalSince1970 * 1000)
}
var currentTime = getCurrentMillis()
Though its working fine in Swift 3.0 but we can modify and use the Date class instead of NSDate in 3.0
Swift 3.0
func getCurrentMillis()->Int64 {
return Int64(Date().timeIntervalSince1970 * 1000)
}
var currentTime = getCurrentMillis()
To get milliseconds for current date.
Swift 4+:
func currentTimeInMilliSeconds()-> Int
{
let currentDate = Date()
let since1970 = currentDate.timeIntervalSince1970
return Int(since1970 * 1000)
}
So far I found gettimeofday a good solution on iOS (iPad), when you want to perform some interval evaluation (say, framerate, timing of a rendering frame...) :
#include <sys/time.h>
struct timeval time;
gettimeofday(&time, NULL);
long millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);
Swift 2
let seconds = NSDate().timeIntervalSince1970
let milliseconds = seconds * 1000.0
Swift 3
let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds
It may be useful to know about CodeTimestamps, which provide a wrapper around mach-based timing functions. This gives you nanosecond-resolution timing data - 1000000x more precise than milliseconds. Yes, a million times more precise. (The prefixes are milli, micro, nano, each 1000x more precise than the last.) Even if you don't need CodeTimestamps, check out the code (it's open source) to see how they use mach to get the timing data. This would be useful when you need more precision and want a faster method call than the NSDate approach.
http://eng.pulse.me/line-by-line-speed-analysis-for-ios-apps/
// Timestamp after converting to milliseconds.
NSString * timeInMS = [NSString stringWithFormat:#"%lld", [#(floor([date timeIntervalSince1970] * 1000)) longLongValue]];
I needed a NSNumber object containing the exact result of [[NSDate date] timeIntervalSince1970]. Since this function was called many times and I didn't really need to create an NSDate object, performance was not great.
So to get the format that the original function was giving me, try this:
#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv,NULL);
double perciseTimeStamp = tv.tv_sec + tv.tv_usec * 0.000001;
Which should give you the exact same result as [[NSDate date] timeIntervalSince1970]
CFAbsoluteTimeGetCurrent()
Absolute time is measured in seconds relative to the absolute reference date of Jan 1 2001 00:00:00 GMT. A positive value represents a date after the reference date, a negative value represents a date before it. For example, the absolute time -32940326 is equivalent to December 16th, 1999 at 17:54:34. Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.
This is basically the same answer as posted by #TristanLorach, just recoded for Swift 3:
/// Method to get Unix-style time (Java variant), i.e., time since 1970 in milliseconds. This
/// copied from here: http://stackoverflow.com/a/24655601/253938 and here:
/// http://stackoverflow.com/a/7885923/253938
/// (This should give good performance according to this:
/// http://stackoverflow.com/a/12020300/253938 )
///
/// Note that it is possible that multiple calls to this method and computing the difference may
/// occasionally give problematic results, like an apparently negative interval or a major jump
/// forward in time. This is because system time occasionally gets updated due to synchronization
/// with a time source on the network (maybe "leap second"), or user setting the clock.
public static func currentTimeMillis() -> Int64 {
var darwinTime : timeval = timeval(tv_sec: 0, tv_usec: 0)
gettimeofday(&darwinTime, nil)
return (Int64(darwinTime.tv_sec) * 1000) + Int64(darwinTime.tv_usec / 1000)
}
Try this :
NSDate * timestamp = [NSDate dateWithTimeIntervalSince1970:[[NSDate date] timeIntervalSince1970]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss.SSS"];
NSString *newDateString = [dateFormatter stringFromDate:timestamp];
timestamp = (NSDate*)newDateString;
In this example, dateWithTimeIntervalSince1970 is used in combination of the formatter #"YYYY-MM-dd HH:mm:ss.SSS" that will return the date with year, month, day and the time with hours, minutes, seconds, and milliseconds. See the example : "2015-12-02 04:43:15.008". I used the NSString to be sure that the format will be has written before.
func currentmicrotimeTimeMillis() -> Int64{
let nowDoublevaluseis = NSDate().timeIntervalSince1970
return Int64(nowDoublevaluseis*1000)
}
let timeInMiliSecDate = Date()
let timeInMiliSec = Int (timeInMiliSecDate.timeIntervalSince1970 * 1000)
print(timeInMiliSec)
This is what I used for Swift
var date = NSDate()
let currentTime = Int64(date.timeIntervalSince1970 * 1000)
print("Time in milliseconds is \(currentTime)")
used this site to verify accuracy http://currentmillis.com/
NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); //double
long digits = (long)time; //first 10 digits
int decimalDigits = (int)(fmod(time, 1) * 1000); //3 missing digits
/*** long ***/
long timestamp = (digits * 1000) + decimalDigits;
/*** string ***/
NSString *timestampString = [NSString stringWithFormat:#"%ld%03d",digits ,decimalDigits];
[NSDate timeIntervalSinceReferenceDate] is another option, if you don't want to include the Quartz framework. It returns a double, representing seconds.

Resources