开发者

How can I extract the hours, min, sec from the below mentioned format

I am making an iphone application in which I want to implement the alarm co开发者_开发知识库ncept. I am using time picker for time but I am getting the time 2011-08-17 17:00:45 +0530 in this format. Now I want to get the hours, min and seconds different by using range concept or any other concept. How can I do it. Please help me.

Thanks in advance.


Try this

NSDateFormatter *format = [[[NSDateFormatter alloc]init] autorelease];
[format setDateFormat:@"HH:mm:ss"];
NSString strTime = [NSString stringWithFormat:@"%@",[format stringFromDate:yourDate]];  

And then separate the string into components :

NSArray *arr = [str componentSeparatedBy:@" "];  
NSString *strHours = [arr objectAtIndex:0];  
NSString *strMinutes = [arr objectAtIndex:1];
NSString *strSeconds = [arr objectAtIndex:2];  

Now convert hours and minutes into seconds :

int iHours = [strHours intValue];
if(iHours>12)    //Check for hour more than 12:00 eg 17:00
{
iHours = iHours - 12;
}

int iMinutes = [strMinutes intValue];

int iSeconds = [strSeconds intValue];

intTotalSeconds = (60*60*iHours) + (60*iMinutes) + iSeconds;

iTotalSeconds are the total seconds you require.


If you want to convert the String to NSDate use:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init]
[format setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZZ"];
NSDate* foo = [dateFormatter dateFromString:yourDateString];

After that you can convert the NSDate to NSDateComponents and get the seconds, minutes etc. from them.

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:
(NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:foo];
NSInteger second = [component second];
NSInteger minute = [component minute];


Either do a mashup of @Nitish and @cortez's answers (use one DateFormatter to parse the date string, and another to output it in your preferred format), or:

Download and include RegexKitLite in your project.

Then go:

#import "RegexKitLite.h"
NSString *timeString = @"2011-08-17 17:00:45 +0530";
NSString *regex = @"\d{2}:\d{2}:\d{2}";
NSString *timeComponent = [timeString stringByMatching:regex capture:1];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜