Hi !
I got a string : 2012-11-07 15:22:06
and I want to do a NSDateFormatter
on it. I do it :
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH:mm, MMMM d, yyyy"];
NSString *date = [[NSString alloc] initWithFormat:@"%@", [df dateFromString:myString]];
But it doesn't work, it returns " (null)
".
Hope that somebody will help me.
Thanks
so the format you set, is [df setDateFormat:@"HH:mm, MMMM d, yyyy"];
the string myString is @"2012-11-07 15:22:06"
=> doesnt match
--- so what I gathered reading your comments on other answers:
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
@autoreleasepool {
NSString *myString = @"2012-11-07 15:22:06"; //yyyy-MM-dd HH:mm:ss
//convert to date
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-DD HH:mm:ss"];
NSDate *myDate = [df dateFromString:myString];
NSLog(@"%@", myDate); //2012-01-07 14:22:06 +0000
//output it in natural language
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setTimeStyle:NSDateFormatterNoStyle];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setLocale:usLocale];
NSLog(@"%@", [df stringFromDate:myDate]); //Jan 7, 2012
}
}
Your format isn't even close to the string's format. Use:
yyyy-MM-dd HH:mm:ss
Use this format: yyyy-MM-dd HH:mm:ss to get the format: 2012-11-07 15:22:06.
To get the format :7th November 2012 Use this function:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSString *string=[dateFormatter stringFromDate:date];
NSDate *newDate=[dateFormatter dateFromString:string];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.