What's the proper way of rounding NSDate on iOS? - objective-c

I need to get the current date, but ignoring minutes and seconds, and then calculate an interval.
For example say that it's 7:30am right now, and I need to see how many hours it is until 5pm the next day, not counting the minutes, which means 7:30am should equal to 7am in this scenario, and the result should be 22 hours.
This could be easily done with
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
assuming that I'm able to create both ends of the interval.
The only option I thought of is using NSDateFormatter to output the current date into a string without the minutes, and then parse it back. But that doesn't seem like a very elegant and efficient solution.
What I basically need to do is trim a NSDate to a specific precision, such as days, and trim the rest (7:50 to 7:00, etc.).
Or is there any simple way I can do this the smarter way, where 7:50 gets roudned to 8:00 instead of 7:00?
I need to do this on iOS 5.

The calculations can be done with NSCalendar, instead of parsing you can use NSDateComponents.
When you take the hours and minutes from NSDateComponents, you can easily apply your rounding and convert the components back to a date.

Related

Is it OK to operate with seconds produced by NSDate timeIntervalSince1970?

Since NSDate represents "a single point in time, independent of any particular calendrical system or time zone", is it OK to make direct calculations with seconds given by its methods like timeIntervalSince1970?
I mean operations like add and subtract of two NSTimeInterval (aka double) values rather than using dateByAddingTimeInterval: or NSCalendar method like - (nullable NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSCalendarOptions)opts.
What issues would have such direct calculations?
Adding may make less sense, but subtracting does make sense if you want to find the difference in time between two dates.
What you want to note, however, is that you should only go for the seconds, minutes, hours, days, weeks difference from your subtraction
But to find the difference in months and years, you will want to use the NSDate API. Months and years are not constant
Likewise with adding dates, if you want to add seconds, minutes, hours, days, weeks. Those are constant and easy to add. But Months and Years will trip you up

Time Addition in Sql Server

I have two time value like
Time1=23:59:59:999
Time2=23:59:59:999
when i add up these two time (Time1+Time2) and i want result will be 47:59:58 rather than 23:59:58.
How can i do this? please suggest!!
Let's look at times and durations:
A datetime is a moment in time, say June 28, 1978 at 15:23.
A time without a datepart is a repetitive moment in time, e.g. "I get up every day at 7:00". (This is what you are using. But I get up at 8:00 and go to sleep at 23:00 doesn't make 8 + 23 = 31. It makes no sense to add times.)
Then there is timespan (e.g. from 2016-01-01 3:00 to 2016-01-02 13:00).
And then there is duration (e.g. six minutes). This is what you want to deal with.
You are storing a duration in a time, which is not really the appropriate data type. As SQL Server does not provide a special data type for a duration, you can use a numeric type for this and store seconds or microseconds or whatever you think appropriate. These you can easily add (provided both values have the same unit, e.g. microseconds).
As to displaying the duration you can write a function providing you with the format you like best for a duration (e.g. '913 days, 9 hours, 5 minutes, and 55.123 seconds').
Actually, that is really hard in SQL Server. How about '1 23:59:58'? If so:
select cast(time1 as datetime) + time2
If you actually want the format in HH:MM:SS format, then you will need to do a lot of string manipulation.

Most efficient way to convert a NSDate object with a given time to one with the same time and the current date

I'm currently creating a scheduling application that deals with schools schedules. Each schedule has an array of period objects that contains both a start and an end time. Currently I have these times stored as NSDate objects, where only the time is really relevant and each NSDate object has some arbitrary date associated with it that is largely insignificant to my application (it's whatever the UIDatePicker assigns to it, but I only use the TimePickerMode). I do a number of things with these dates. First, I use an NSDateFormatter to output a string representation of the time for each period in a UITableView. I then also attempt to find the current period in the day by comparing the current time, fetched by [NSDate date], to the start and end time. But I am having trouble deciding the best way to do this.
Currently, I use an NSDateFormatter to convert the start and end times to strings, and then back to dates that now have a date the same as today's date. Then after that I can do my date comparisons using - (NSComparisonResult)compare: comparing the start and end dates to the current date. However, I could see this as being very inefficient.
Other possible ways could be to convert each NSDate to NSDateComponents, then use NSCalendar to convert that back into an NSDate with the current date and the same original time.
Or, I could take a different approach and ditch the NSDate storage technique altogether. Instead I could store each start and end time as NSDateComponents, then it would be simple enough to output a formatted version of the time for the UITableView, and then I could convert the date obtained by [NSDate date] to NSDateComponents to be used for logical comparisons to obtain the current period.
I see three or four different ways of going about this, and actually after talking it out I I'm pretty confident the final way I discussed would be the most efficient as it requires the least amount of runtime conversions between different types of date objects. I'm just looking for other people's inputs.
The problem with using NSDate to store a time-of-day is that its value is dependent on the time zone. If the time zone or DST changes while your app is running in the foreground or background, then all of your times will suddenly be wrong. Ditto if you actually save NSDate values to disk. (One option is to set your app's default time zone to UTC, but then your app's idea of "now" will be incorrect to the user).
I would store the time separately and implement methods to convert to and from NSDate. You could store the time using NSDateComponents, or you could just store it as a single integer (say, minutes past midnight) which makes it trivial to compare two times.
When converting minutes to and from NSDate you use NSDateComponents, and you need to make sure that your UIDatePickers, NSCalendars, and NSDateFormatters are using the same time zone, which by default is the local time zone.
It seems like you're worried about the overhead that NSDateFormatter currently levies on your program to synchronize the day of your periods and the current date. But really, you don't care about the date at all, you just want the time since the beginning of the day.
Why not cut out the middleman? Store the start and end times as NSTimeIntervals, which are really just doubles. Mod the start and end times by 86,400, the seconds in a day, in order to distill the time down to simply the time in seconds after the start of a new day. You don't really care what day it represents, except that that day is represented as second 0.
Then whenever you pull the current NSDate, mod its NSTimeInterval by 86,400 to obtain the time in seconds and compare it against the stored period values. The only object conversion involved in the whole process would be using the primitive timeIntervalSinceReferenceDate. The rest are simple mod and comparison operators, and you get to store your period numbers as simple NSTimeIntervals.

Adding two NSDate

I've got two NSDate, date and time. I'd like to add them in such a manner that I get the date from date and time from time. Any suggestions on how I do this?
Cheers
Nik
If I got you right NSDates -dateByAddingTimeInterval: together with -timeIntervalSinceDate: are what you looking for.
hth
–f
Use NSCalendars components:fromDate: to get the components of the two dates.
Then reassemble them as needed using dateFromComponents:.
I've got two NSDate, date and time.
Sounds like you're going about it wrong.
An NSDate represents a specific moment in time (X seconds since the epoch). An NSDate is not simply “x o'clock” or “this date on the calendar”, and you shouldn't attempt to combine them as if they were because effects such as DST may make your computation wrong (in some time zones, some dates have two 1:00 hours, and some have no 2:00 hours).
Consider using an NSDatePicker or UIDatePicker (as appropriate) to let the user enter the date and time from a single place. Not only is this easier for you to do, it'll also give more correct results.
If you're reading the two pieces separately from a file or similar source, and you don't control the format (so you can't order the generating side to emit dates with their times in one value), you'll need to do one of two things:
If possible, combine the two strings. For example, an ISO 8601 date (e.g., “2010-05-10”) and an ISO 8601 time (e.g., “23:20:19-0700”) can be concatenated with a ‘T’ between them to form a valid, fully-specified ISO 8601 date (“2010-05-10T23:20:19-0700”). You can then pass this single string to a properly-configured NSDateFormatter.
If, for some reason, you can't combine the strings meaningfully, parse them yourself and fill out a single NSDateComponents object yourself.
This will not be pleasant, but correctness is important, and a bug (incorrect date parsing) that only happens in two hours out of every year for only some of your users will be maddening.
The goal is to produce exactly one NSDate object that completely describes the date and time in question. This is the only way to ensure that, in all circumstances, you get the correct NSDate value.

What is the range for the DATE type in Core Data?

I'm putting together an application that will require the recording of dates as far back as the BC range; can Core Data's date type handle this, or do I need to define another entity to properly record and format dates?
NSDate works using NSTimeInterval which is a double.
always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years.
I'm not going to work out how far back in time a double will go (order of +/- 10^300 seconds or so), but I think you will be safe to use it for the BC ranges. For example: 1,000 years is about 3x10^11 seconds.
Perhaps this is useful, NSDate distantPast gives you:
0001-12-31 19:43:12 -041648
and NSDate distantFuture gives you:
4000-12-31 21:00:00 -0300