Convert string to time (not date) [duplicate] - iphone

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
hours minutes seconds to seconds ios
I have a time formatted as such
// format: HH:mm:ss,AAA
// example for 2 hours, 35 minutes, 15 seconds, and 207 milliseconds
02:35:15,207
I'm trying to convert that into seconds as a double. The above example would turn into:
// 2 hrs * 3600 + 25 min * 60 + 15.207
9315.207
I figure I can pick apart each element with a scanner, but I'm thinking there's probably an easier way. I tried using NSDateFormatter but I need this as a double, not as an NSDate. Any suggestions? Thanks.
Further FYI
This is for use with the MPMoviePlayer and the currentTime property is a double. For any given section where I have data to show, I am checking if dataStartTime <= playerTime < dataEndTime. So I'm using double because that's the type for currentTime already.

Here is the solution, the idea is simple get two date one with your time and one with 00:00:00,000 time then take difference of their time.
- (double)secondsFromString:(NSString*)str {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss,SSS"];
NSString *dateString = #"1970-01-01";
NSDate *date = [formatter dateFromString:[NSString stringWithFormat:#"%# %#",dateString,str]];
NSDate *refDate = [formatter dateFromString:[NSString stringWithFormat:#"%# 00:00:00,000",dateString]];
double time = [date timeIntervalSince1970] - [refDate timeIntervalSince1970];
return time;
}

Related

Math issue using timeIntervalSince 1970

I am trying to find how many milliseconds into the current day we are. I can't find a method to return the time in milliseconds ignoring date, so I figured I could calculate it off of the value returned by timeIntervalSince 1970 method.
I did this:
NSLog(#"%f", [[NSDate date] timeIntervalSince1970]);
2013-05-21 16:29:09.453 TestApp[13951:c07] 1369171749.453490
Now my assumption is that, since there are 86,400 seconds in a day I could divide this value by 86400 and get how many days have elapsed since 1970. Doing this gives me 15846.8952483 days. Now, if my assumption holds, I am 89.52483% through the current day. So multiple 24 hours by 86.52659% would give me a current time of the 21.4859592 hour or about 09:29 PM. As you can see from my NSLog this is about 5 hours from the real time, but I believe the interval returned is GMT so this would be 5 hours ahead of my time zone.
So I figured, well what the heck, I'll just roll with it and see what happens.
I cut off the decimal places by doing:
float timeSince1970 = [[NSDate date] timeIntervalSince1970]/86400.0;
timeSince1970 = timeSince1970 - (int)timeSince1970
Then calculate the milliseconds that have taken place thus far today:
int timeNow = timeSince1970 * 86400000;
NSLog(#"%i", timeNow);
2013-05-21 16:33:37.793 TestApp[14009:c07] 77625000
Then I convert the milliseconds (which still seem appropriate) to NSDate:
NSString *timeString = [NSString stringWithFormat:#"%d", timeNow];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"A"]
NSDate *dateNow = [dateFormatter dateFromString:timeString];
NSLog(#"%#", dateNow);
2013-05-21 16:29:09.455 TestApp[13951:c07] 2000-01-02 03:29:00 +0000
And there is my problem. Rather than returning a 2000-01-01 date with some hours and minutes attached, it is returning a 2000-01-02 date. Why!?
EDIT
I got it working by "removing" the extra 5 hours I noted in the above with:
int timeNow = (timeSince1970 * 86400000) - (5 * 60 * 60 * 1000);
I don't understand why this is necessary though. If someone can explain I'd greatly appreciate it.
EDIT 2
Perhaps I should be asking a more elementary question about how to accomplish the task I'm trying to accomplish. I care about times (for example, 4pm is important but I could care less about the date). I've been storing these in NSDates created by:
[dateFormatter setDateFormat:#"hh:mm a"];
[dateFormatter dateFromString#"04:00 PM"];
All this seems to be going fine. Now I want to compare current time to my saved time and find out if it is NSOrderedAscending or NSOrderedDescending and respond accordingly. Is there a better way to be accomplishing this?
You need to use NSCalendar to generate NSDateComponents based on right now, then set the starting hour, minute, and second all to 0. That will give you the beginning of today. Then you can use NSDate's -timeIntervalSinceNow method to get back the time elapsed between now and your start date.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
// BUILD UP NSDate OBJECT FOR THE BEGINNING OF TODAY
NSDateComponents *comps = [cal components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: now];
comps.hour = 0;
comps.minute = 0;
comps.second = 0;
// USE CALENDAR TO GENERATE NEW DATE FROM COMPONENTS
NSDate *startOfToday = [cal dateFromComponents: comps];
// YOUR ELAPSED TIME
NSLog(#"%f", [startOfToday timeIntervalSinceNow]);
Edit 1
If you're just looking to compare some NSDateObjects you can see if the time interval between then and now is negative. If so, that date is in the past.
NSDate *saveDate = [modelObject lastSaveDate];
NSTimeInterval difference = [saveDate timeIntervalSinceNow];
BOOL firstDateIsInPast = difference < 0;
if (firstDateIsInPast) {
NSLog(#"Save date is in the past");
}
You could also use compare:.
NSDate* then = [NSDate distantPast];
NSDate* now = [NSDate date];
[then compare: now]; // NSOrderedAscending
The part of your question that says that you want to calculate "how many milliseconds into the current day we are" and then "4pm is important but I could care less about the date" makes it not answerable.
This is because "today" there could have been a time change, which changes the number of milliseconds since midnight (by adding or subtracting an hour, for instance, or a leap second at the end of a year, etc....) and if you don't have the date, you can't determine the number of milliseconds accurately.
Now, to address your edited question: If we assume today's date, then you need to use the time that you have stored and combine it with today's date to get a "specific point in time" which you can compare to the current date and time:
NSString *storedTime = #"04:00 PM";
// Use your current calendar
NSCalendar *cal = [NSCalendar currentCalendar];
// Create a date from the stored time
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"hh:mm a"];
NSDate *storedDate = [dateFormatter dateFromString:storedTime];
// Break it up into its components (ie hours and minutes)
NSDateComponents *storedDateComps = [cal components:NSHourCalendarUnit | NSMinuteCalendarUnit
fromDate:storedDate];
// Now we get the current date/time:
NSDate *currentDateAndTime = [NSDate date];
// Break it up into its components (the date portions)
NSDateComponents *todayComps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:currentDateAndTime];
// Combine with your stored time
todayComps.hour = storedDateComps.hour;
todayComps.minute = storedDateComps.minute;
// Create a date from the comps.
// This will give us today's date, with the time that was stored
NSDate *currentDateWithStoredTime = [cal dateFromComponents:todayComps];
// Now, we have the current date and the stored value as a date, so it is simply a matter of comparing them:
NSComparisonResult result = [currentDateAndTime compare:currentDateWithStoredTime];
it is returning a 2000-01-02 date. Why!?
Because your dateFormatter uses the current system locale's timezone.
If you insert ...
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
... your date formatter will interpret the string correctly. But why not creating the date directly:
NSDate *dateNow = [NSDate dateWithTimeIntervalSinceReferenceDate:timeNow];

Xcode - NSTimeInterval Years double value, how to get MORE decimals?

i wan't to know exactly how many years it is between 2 NSDate's. (current Date and Date picker date)
i'm using NSTimeInterval (seconds) how to make it to years?
This code will make the value to Years:
NSTimeInterval distanceBetweenDates = [now timeIntervalSinceDate:date];
double secondsInAnYear = 31536000;
double YearsBetweenDates = distanceBetweenDates / secondsInAnYear;
NSString *dateString = [NSString stringWithFormat:#"%f", YearsBetweenDates];
labelView.text = dateString;
but i just get 6 decimals!
i want more than 6 decimals. How?
Take a look at -[NSCalendar (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts]. This does the calculation correctly. You can't assume a year always is exactly 31536000 seconds (leap year, or even those leap second(s) that get added occasionally).
Have you tried using %lf which is the designated specifier for long float/double values?
NSString *dateString = [NSString stringWithFormat:#"%lf", YearsBetweenDate];

how to convert a unix timestamp into nsdate in iphone [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Create NSDate from Unix timestamp
I have an application where i am receiving date from json in unix timestamp format.This is the timestamp that i am receiving from json '1357178589630'.How to convert this timestamp into correct nsdate.I have used the following code for conversion but it is not working properly.This is my code:
double timestampval = [[updates objectForKey:#"timestamp"] doubleValue];
NSTimeInterval timestamp = (NSTimeInterval)timestampval;
NSDate *updatetimestamp = [NSDate dateWithTimeIntervalSince1970:timestamp];
When the timestamp is converted to nsdate using datewithtimeIntervalSince1970,in the updatetimestamp variable it displays '44977-04-11 12:40:30 +0000'
Try this one:
Might be you are getting timestamp is milli seconds instead of seconds, so you divide it by 1000.
EDIT Newer:
double timestampval = [[updates objectForKey:#"timestamp"] doubleValue]/1000;
NSTimeInterval timestamp = (NSTimeInterval)timestampval;
NSDate *updatetimestamp = [NSDate dateWithTimeIntervalSince1970:timestamp];
Previous :
double unixTimeStamp =1304245000;
NSTimeInterval timeInterval=unixTimeStamp/1000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setLocale:[NSLocale currentLocale]];
[dateformatter setDateFormat:#"dd-MM-yyyy"];
NSString *dateString=[dateformatter stringFromDate:date];
[NSDate dateWithTimeIntervalSince1970:timestamp] is correct. Seems that your timestamps is wrong.
Instead 1357178589630 it should be 1357178589.
Try here.
Update: as per Martin comment above.
Just divide the value by 1000.
try this code..
NSDate *dateTraded = [NSDate dateWithTimeIntervalSince1970 :[[updates objectForKey:#"timestamp"] integerValue]];
and Unix timestamps are in seconds, the value you have looks like a number of milliseconds since 1st January 1970. If you divide by 1000, you get 1264396813, which according to http://www.onlineconversion.com/unix_time.htm

How do you get a numerical value from a UIDatepicker?

i am developing an app that involves getting a value from a datepicker and subtracting it from the date displayed on the actual iphone. how will i do this? i have looked everywhere for an answer!
thanks Rafee
You should implement datePickerValueChanged as the selector, and implement like this.
- (void)datePickerValueChanged:(UIDatePicker*) date_Picker{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
NSString *dateFromPicker = [NSString stringWithFormat:#"%#",[df stringFromDate:date_Picker.date]];
// calculating time difference now
NSDate *timeRightNow = [NSDate date];
NSTimeInterval diff = [timeRightNow timeIntervalSinceDate:date_Picker.date];
// The difference should always be in seconds. Here, 3628800 represents 6 weeks.
if (diff > 3628800){
// Do something if the entered date is six weeks from the iPhone date.
}
}

How to tell amount of hours since NSDate

I initiated an NSDate with [NSDate date]; and I want to check whether or not it's been 5 hours since that NSDate variable. How would I go about doing that? What I have in my code is
requestTime = [[NSDate alloc] init];
requestTime = [NSDate date];
In a later method I want to check whether or not it's been 12 hours since requestTime. Please help! Thanks in advance.
NSInteger hours = [[[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:requestTime toDate:[NSDate date] options:0] hour];
if(hours >= 5)
// hooray!
int seconds = -(int)[requestTime timeIntervalSinceNow];
int hours = seconds/3600;
Basically here I'm asking how many seconds have passed since we first got our requestTime. Then with a little math magic, aka dividing by the number of seconds in an hour, we can get the number of hours that have passed.
A word of caution. Make sure you use the "retain" keyword when setting the requesttime. xcode likes to forget what NSDate objects are set to without it.
requestTime = [[NSDate date] retain];
Try using this method, or something along these lines.
- (int)hoursSinceDate :(NSDate *)date
{
#define NUBMER_OF_SECONDS_IN_ONE_HOUR 3600
NSDate *currentTime = [NSDate date];
double secondsSinceDate = [currentTime timeIntervalSinceDate:date];
return (int)secondsSinceDate / NUBMER_OF_SECONDS_IN_ONE_HOUR;
}
You can then do a simple check on the integer hour response.
int hours = [dateUtilityClass hoursSinceDate:dateInQuestion];
if(hours < 5){
# It has not yet been 5 hours.
}