Lokesh Chowdary
Lokesh Chowdary

Reputation: 736

Remove milliSeconds from String in iOS

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...

Upvotes: 2

Views: 2028

Answers (3)

user5917312
user5917312

Reputation:

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

Upvotes: 1

Gaurav Patel
Gaurav Patel

Reputation: 532

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

Upvotes: 0

Prashant Tukadiya
Prashant Tukadiya

Reputation: 16426

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

Upvotes: 7

Related Questions