Rocky
Rocky

Reputation: 1423

how to take a date without time in iphone

I am try to remove time from date how to do this i try this code it not working proper where i am wrong

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDate *todaysDate = [NSDate date]; 
//NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
NSDateComponents*dateComponents = [gregorian components:NSDayCalendarUnit fromDate:todaysDate];

[dateComponents setDay:1]; 
app.selectionData.fromDateSelected = [gregorian dateByAddingComponents:dateComponents toDate:todaysDate options:0]; 
//[dateComponents release]; 
[gregorian release];

Upvotes: 0

Views: 1654

Answers (3)

Parth Bhatt
Parth Bhatt

Reputation: 19469

Try this out. This works for me

NSDate *todaysDate = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSString *stringDate = [dateFormat stringFromDate:todaysDate];
NSLog(@"stringDate: %@",stringDate);
[dateFormat release];

EDIT:

 NSDate *today = [NSDate date];
    NSTimeInterval secondsPerDay = 24 * 60 * 60;    
    NSDate *date = [today addTimeInterval:secondsPerDay]; 
    //Change NSDate *date = [tomorrow addTimeInterval:-secondsPerDay]; for yesterday
    NSDate *tomorrow = date;
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSString *stringDate = [dateFormat stringFromDate:tomorrow];
    NSLog(@"stringDate: %@",stringDate);
    [dateFormat release];

Hope this helps you.

Upvotes: 0

krammer
krammer

Reputation: 2658

To only get the date, you can use NSDateFormatter

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString* currentDate = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release]; 

You can also supply your own format for the date. For ex:

[dateFormattter setDateFormat:@"yyyy-mm-dd"];

You can refer to UTS #35 and Date Formatting Guide for more options on formatting.

Upvotes: 1

EmptyStack
EmptyStack

Reputation: 51374

Are you trying to do this?

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
int comps = NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;
NSDateComponents *dateComponents = [gregorian components:comps fromDate:[NSDate date]]; 
[dateComponents setDay:[dateComponents day] + 1];
app.selectionData.fromDateSelected = [gregorian dateFromComponents:dateComponents]; 
[gregorian release];

Upvotes: 3

Related Questions