从 iOS 中的字符串中删除毫秒

Remove milliSeconds from String in iOS

正在尝试从 String(date) 中删除毫秒

NSString *dateString = @"2016-05-16 13:17:34.674194";
 NSDateFormatter* formater = [[NSDateFormatter alloc] init];
 [formater setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
 NSDate *date = [formater dateFromString:dateString];
 NSLog(@"%@",[formater stringFromDate:date]);

我得到空值

我期待 o/p 类似(没有毫秒)

"2016 年 6 月 5 日 13:17:34"

请推荐...

试试这个:-

NSString *dateString = @"2016-05-16 13:17:34.674194";
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SS";     
NSDate *yourDate = [dateFormatter dateFromString:dateString];
dateFormatter.dateFormat = @"dd-MMM-yyyy HH:mm:ss";
NSLog(@"%@",[dateFormatter stringFromDate:yourDate]);

复制并粘贴此代码可完美运行

NSString *dateString = @" ";
NSDateFormatter* dateFormatter1 = [[NSDateFormatter alloc] init];
dateFormatter1.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
NSDate *yourDate = [dateFormatter1 dateFromString:dateString];
dateFormatter1.dateFormat = @"dd/MM/yyyy HH:mm:ss";
NSLog(@"%@",[dateFormatter1 stringFromDate:yourDate]);

这是输出

2016-05-16 16:43:53.639 StackLearn[6376:151614] 16/05/2016 13:17:34

Rule of Date formatter is you must set date format same like your string while you are getting date from string , if mismatch then you will get null

工作完美

NSString *dateString = @" ";
NSDateFormatter* dateFormatter1 = [[NSDateFormatter alloc] init];
dateFormatter1.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
NSDate *yourDate = [dateFormatter1 dateFromString:dateString];
dateFormatter1.dateFormat = @"dd/MM/yyyy HH:mm:ss";
NSLog(@"%@",[dateFormatter1 stringFromDate:yourDate]);