Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate: Extract Date ONLY

I'm using the code below to extract the date only from NSDate. What am I doing wrong?

    NSDate* now = [NSDate date];
    NSLog(@"Now Date %@",now);
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"dd-MM-yyyy";
    NSString *stringDate = [format stringFromDate:now];
    NSDate *todaysDate = [format dateFromString:stringDate];
    NSLog(@"Today's Date without Time %@", todaysDate);

Log:

2014-06-21 12:27:23.284 App[69727:f03] Now Date 2014-06-21 19:27:23 +0000
2014-06-21 12:27:23.285 App[69727:f03] Today's Date without Time 2014-06-21 07:00:00 +0000

Why am I getting: 07:00:00 +0000 at the end?

I would like to get an NSDate in the in the following format:

2014-06-21 00:00:00 +0000

Having 0's for time, seconds, etc. is not important.

like image 450
user1107173 Avatar asked Jun 21 '14 19:06

user1107173


4 Answers

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];

should work

like image 186
dietbacon Avatar answered Nov 16 '22 00:11

dietbacon


Another solution: using NSCalendar:

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:1]]; // I'm in Paris (+1)
NSDateComponents *comps = [cal components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];

comps.hour = 0;
comps.minute = 0;
comps.second = 0;

NSDate *newDate = [cal dateFromComponents:comps ];

NSLog(@"date: %@",newDate);

Adjust timezone param, you will receive something like: date: 2014-06-21 00:00:00 +0000

like image 27
Duyen-Hoa Avatar answered Nov 16 '22 00:11

Duyen-Hoa


If you don't care about the time, NSDate is not the right storage structure for you. An NSDate represents a specific moment in time - there is no NSDate without a time. What you're seeing is the logged description of an NSDate, which is the full printout in GMT.

If you want to keep track of the year, month and day only, then use NSDateComponents instead, and extract only the components you are interested in. You can then use the components object and pass it around as you like.

like image 36
jrturton Avatar answered Nov 16 '22 00:11

jrturton


NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];

With the code above, the NSDate object will HAVE time. But the string will be a date only text.

like image 34
gsach Avatar answered Nov 15 '22 22:11

gsach