iPHONE SDK - Subtracting a time given another time - iphone

having trouble with this. i need to come up with a logic code.
How do i, given 2 set of times. subtract one from the other and change it all to seconds.
Lets say i have '12:00:00' and '15:00:00'
Now i want to subtract 12:00:00 from 15:00:00 so the result will be 03:00:00. Then change it all to seconds so that will be 10800 seconds
i already have two sets of time in an NSString after being Formatted with a NSDateFormatter

This is what you need to look for : NSDate -(NSTimeInterval)timeIntervalSinceDate
Convert your string to an NSDate and call this method [thisDate timeIntervalSinceDate:thatDate] will return you an NSTimeInterval, type double

Related

how can I store different times from stopwatch

I am confused regarding to calculation of two different times. In my game, when game starts then timer gets started (like stop watch) and it stops when game gets finished. Now I have to store best low time among previous time list.
I am getting time in hh:mm:ss format. how can I store this time so that i can compare it with different time in list ? I tried to store this value in NSString, but the comparison fails.
EDITED :
Let me clarify the Question :
For example how can I store different times from stopwatch and how to sort it in ascending order ?
any suggestions?
Thanks...
Take two NSDates, one at the game start and one at game finish, then calculate the difference.
NSDate *startDate = [NSDate date]; // At game start
NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:startDate]; // At game finish
NSlog(#"interval: %.2f", interval);
You could use
long stamp = (long)[[NSDate date] timeIntervalSince1970];
for each of your time-relevant situation since the posted code is giving you a UNIX-timestamp. This timestamp can be used in arithmetic operations/comparisons which should be exact what you are looking for.

How can I create a count up timer with the format seconds:milliseconds?

I'm diving into iOS development and I'm trying to create a count up timer in one of my views. I have the NSTimer code figured out to call a selector once every 0.04 seconds that updates the UILabel. Where I'm having trouble is with the formatting of the current time (starting initially at 00:00). I figured the best way to do this was using the NSDate class, and related classes (NSDateFormatter, NSDateComponents, etc.), but the manipulating of the dates and formats is really confusing me and the code is getting unwieldy quickly. I was hoping there are some SO users that are comfortable using the NSDate class that could help me figure out a simple way to calculate the current time for a count up timer and convert it to an NString with the format 'seconds:milliseconds'.
I'd be happy to post my initial attempt at the NSDate code if requested, but I won't initially because it's really of no use and embarrassing :)
If you just want to display time elapsed since you started your timer you can store starting date somewhere (say, startDate variable) and calculate time interval using current date. Something like the following should work:
NSTimeInterval passed = [[NSDate date] timeIntervalSinceDate: startDate];
double intPart;
double fract = modf(passed, &intPart);
label.text = [NSString stringWithFormat:#"%d:%.2f", (int)intPart, fract];

Is there an objective-c/iPhone version of currentTimeMillis() from Java?

I need to time some events in the app I'm working on. In Java i used to be able to call currentTimeMillis() but there doesnt seem to be a version in Objective-c. Is there a way to check there current time without creating a NSDate and then parsing this object everytime i need this information?
Thanks
-Code
[[NSDate date] timeIntervalSince1970] * 1000 returns a the same value as currentTimeMillis()
CFAbsoluteTimeGetCurrent() and [NSDate timeIntervalSinceReferenceDate] both return a double starting at Jan 1 2001 00:00:00 GMT.
There's also CFAbsoluteTimeGetCurrent(), which will give you the time in double-precision seconds.
To get very cheap very precise time, you can use gettimeofday(), which is a C Function of the BSD kernel. Please read the man page for full details, but here's an simple example:
struct timeval t;
gettimeofday(&t, NULL);
long msec = t.tv_sec * 1000 + t.tv_usec / 1000;
Instead gettimeofday() you could also use [NSDate timeIntervalSinceReferenceDate] (the class method) and do your calculations with that. But they have the same problem: they operate on "wall clock time". That means your measurement can be off if leap seconds are added while your test is running or at the transition between daylight saving time.
You can use the Mach system call mach_absolute_time() on OS X and iOS. With the information returned by mach_timebase_info() this can be converted to nanoseconds.
The correct answer is [[NSDate date] timeIntervalSince1970]; this will give you current timestamp in milliseconds.
The answer given by #Noah Witherspoon returns current date but the year is not the current matching year.

Doing comparison on NSDates in different timezones?

I have an array of NSDates which I build from strings using [NSDate dateFromString]
In the xml I parsed to get the string there was also a timezone string. As far as I can see in the manual NSDate does not in it self deal with timezones. Do I need to always store this timezone value somewhere and pair it with the belonging NSDate each time I need it?
I also need to figure out that if an event starts in London at 10:00, but I am in Denmark having my iPhone set to danish time my "event started in London" should display at 09:00 o'clock.
Again if an event starts in London at 10:00 o'clock and ends in Denmark at 12:00 o'clock, If I were to compare start time and end time using an iPhone with danish settings I would get that the duration of the event was 02:00 event though 10:00 o'clock in UK and 12:00 o'clock in Denmark is only 1 hour apart.
NSdate works really well for these things in the scope of one timezone, but introducing the timezone part just made everything complicated to me. Is there a way to abstract/hide all these calculations, as I see potential for making a lot of mistakes.
I have been through the NSDateformatter and NSDate guides from Apple, but they are really vague and sports a substantial amount of deprecated code :/
Thanks for any help given.
You should take one standard timezone like UTC/GMT format for all calculation.
According to the NSDate reference, dateWithString: takes an offset to GMT as last component; while it is not a time zone, it is sufficient to perform computation or comparison).
Looking at the NSTimeZone reference, you can use the abbreviationForDate: and the timeZoneWithAbbreviation: to get a NSTimeZone object from a NSDate instance. Once you get the time zone, you have everything you need.
I convert the present date and the date I would like to know if is close, to GMT and then returning the difference. So I changed every thing to deal with differences instead of actual times and dates. A bit like a music score transposed to a different key:)
+ (NSInteger) minutesUntilDate:(NSDate*) date withTimezoneOffset:(NSInteger) GMTOffset
{
NSDate *now = [NSDate date];
NSTimeInterval localTimeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
now = [now addTimeInterval:(localTimeZoneOffset * -1)];
date = [date addTimeInterval:(GMTOffset * 60 * 60) * −1];
return ((NSInteger)[now timeIntervalSinceDate:date] / 60 ) * -1;
}
As soon as you have allocated an NSDate, these do not have timezone information any longer. NSDate is "timezone-less" and is always in GMT. You should make sure that NSDate understand your format correctly when allocating it.
Once you have an NSDate you can make normal calculations and ignore the timezones.
You only need to take care of timezones when reading strings into NSDates and when printing them out.

ASP: convert milliseconds to date

I need to convert a field with milliseconds created by PHP app to a date value. Is there a way to do this using VBScript? or convert to datetime in SQL 2005?
Example: 1113192000 to mm/dd/yyyy hh:mm:ss
Something like the following should work:
Function ConvertPhpToDate(numSeconds)
Dim dEpoch
dEpoch = DateSerial(1970,1,1)
ConvertPhpToDate = DateAdd("s",numSeconds,dEpoch)
End Function
Note, the php time() function returns the number of 'seconds', not milliseconds. http://php.net/manual/en/function.time.php
I think what you are referring to as milliseconds is really the epoch time as returned by the php's time/date functions. You can give this a function a shot to get the epoch time converted to datetime format in ASP:
function epoch2date(myEpoch)
epoch2date = DateAdd("s", myEpoch, "01/01/1970 00:00:00")
end function
Source: http://www.epochconverter.com/epoch/functions.php#asp
msValue = 32312312
dtValue = DateAdd("s", msValue/1000, CDate("1970-01-01 00:00:00"))
Wrap it in a function:
Function TimestampToDate(timestamp)
TimestampToDate = DateAdd("s", timestamp/1000, CDate("1970-01-01 00:00:00"))
End Function
You'll need to have a base time to count the milliseconds from e.g. 1st Jan 1970 or similar.
You then divide the number of milliseconds by 1000 to get the number of seconds - saving the remainder.
Divide the number of seconds by 60 (saving the remainder) to get the number of minutes.
Then 60 again for hours, 24 for days.
Then it get's difficult as you've got leap years to consider. There is another question on this here.
Once you've got your years, days, hours, minutes, seconds and milliseconds you add this to the base date-time to get the date-time represented.
Others have posted code etc. that you might use.