I have a NSStirng
which contains 2013-01-08 07:52:00 +0000
. I would like to separate the date and time in different NSStrings
.
Any help is appreciated .
I have a NSStirng
which contains 2013-01-08 07:52:00 +0000
. I would like to separate the date and time in different NSStrings
.
Any help is appreciated .
Is the format from the server consistent?
Do you need to use the dates and times for anything like sorting etc... or for doing time additions or are you just displaying them?
If you're just displaying them and the format of the string won't change then you can do this...
//assumption 1: the format is <date>space<time>space<timezone>
//assumption 2: the only purpose is to display the values sent from the server.
NSString *dateString = @"2013-01-08 07:52:00 +0000";
NSArray *components = [dateString componentsSeparatedByString:@" "];
NSString *date = components[0];
NSString *time = components[1];
The first thing to do is to convert your date string into an NSDate
:
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate * date = [formatter dateFromString: @"2013-01-08 07:52:00 +0000"];
Then you can use the formatter againt to reverse the process and return a date and time. You can adjust the format of each as required.
[formatter setTimeStyle:NSDateFormatterShortStyle]; // Get the time only
[formatter setDateStyle:NSDateFormatterNone];
NSString * timeString = [formatter stringFromDate: date];
[formatter setTimeStyle:NSDateFormatterNone];
[formatter setDateStyle:NSDateFormatterShortStyle]; // Get the date only
NSString * dateString = [formatter stringFromDate: date];
Try the code below,
NSString *maindateString = @"2013-01-08 07:52:00 +0000";
NSDateFormatter *myFormat = [[NSDateFormatter alloc] init];
[myFormat setDateFormat:@"yyyy-mm-dd hh:mm:ss Z"];
NSDate *mainDateDate = [myFormat dateFromString:maindateString];
[myFormat setDateFormat:@"yyyy-mm-dd"];
NSString *stringDate = [myFormat stringFromDate:mainDateDate];
Check the NSString
stringDate and there is what you need :-)
EDIT: To get the time string, add the following code:
NSDateFormatter *myFormat2 = [[NSDateFormatter alloc] init];
[myFormat2 setDateFormat:@"HH:mm:ss"];
NSString *stringTime = [myFormat2 stringFromDate:mainDateDate];
NSLog(@"%@",stringTime);
Regards
please create a date from that String:
and then use these (or convert them back to string). That's save.
anyway, you should have had a NSDate before that NSString - did you? why not keeping that one?