我有一个文本字段,用户可以用这种格式插入日期和时间: MMDDHHMM(11230530)我希望标签定于11月23日上午5点30分。 我试过了:
NSString *data = [NSString stringWithFormat:@"%@", [date text]];
// Convert string to date object
NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MMdd hh:mm"];
NSDate *dateFromString = [dateFormatter dateFromString:data];
NSLog(@"%@", dateFromString);
// Convert date object to desired output format
[dateFormatter setDateFormat:@"???????????"];// I don't know how to change the format ;-)
data = [dateFormatter stringFromDate:dateFromString];
NSLog(@"%@", data);
[dateFormatter release];
但是我从数据中得到了空白。任何线索?
答案 0 :(得分:10)
使用此代码,
NSString *date = [NSString stringWithFormat:@"11230530"];
NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MMddHHmm"];
NSDate *dateFromString = [dateFormatter dateFromString:date];
NSLog(@"%@", dateFromString);
[dateFormatter release];
dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd MMMM' at 'hhmm a"];
NSString *stringFromDate=[dateFormatter stringFromDate:dateFromString];
//Use this text to display in that textfield
[dateFormatter release];
答案 1 :(得分:2)
以这种方式使用此代码
NSDate *data = [NSDate stringWithFormat:@"%@", [date text]];];
NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MMdd hh:mm"];
NSDate *dateFromString = [dateFormatter dateFromString:data];
NSLog(@"%@", dateFromString);
希望它会有所帮助。