Remove milliSeconds from String in iOS

我怕爱的太早我们不能终老 提交于 2019-12-07 22:38:00

问题


Trying to remove milli seconds from 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]);

and i'm getting null

i'm expecting o/p something like (with out milli seconds)

"06/05/2016 13:17:34"

Please suggest...


回答1:


Copy and paste this Code working Perfectly

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]);

Here is Output

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




回答2:


try this:-

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]);



回答3:


working Perfect

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]);


来源:https://stackoverflow.com/questions/37252296/remove-milliseconds-from-string-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!