Eric Chuang Eric Chuang - 6 months ago 16
Objective-C Question

How can I convert and display this NSDate more efficiently?

Here is my code:

NSDateFormatter *df = [NSDateFormatter alloc]init];
df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *date = [df dateFromString:self.todayRecord.datetime];


self.todayRecord.datetime is a string that looks something like:

2016-02-15 12:33:00


I want to display the same date but without the seconds like this:

2016-02-15 12:33


The way I can think of right now is make another date formatter and just format out the seconds. Something like this:

df.dateFormat = @"yyyy-MM-dd HH:mm";
NSDate *date = [df dateFromString:self.todayRecord.datetime];


I did this and display became (null).

Answer

do like

//create the NSDateFormatter first
NSDateFormatter *df = [NSDateFormatter alloc]init];
// set the date format based on your String
df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// convert the string to date
NSDate *date = [df dateFromString:self.todayRecord.datetime];
// set the final dateformat what the output do you need
df.dateFormat = @"yyyy-MM-dd HH:mm";
// in here you get final output on String
NSString *finalString = [df StringFromdate:date];
// in here you get final output on date 
NSDate *FinalDate = [df dateFromString:finalString];
Comments