Showing posts with label NSDate. Show all posts
Showing posts with label NSDate. Show all posts

Wednesday, 13 July 2016

Update hours/minutes/seconds in NSDate | Get current date from NSDate but set custom time

 
// 24 hour date format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

// Now date + 12 am time fixed (00:00:00)
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
NSDate *nowDate = [calendar dateBySettingHour:0 minute:0 second:0 ofDate:[NSDate date] options:0];
NSString *str = [dateFormatter stringFromDate:nowDate];
NSLog (@"String is: %@", str);

Wednesday, 22 August 2012

Combine two NSDates | Add date component + time component = NSDate

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// Extract date components into components1
NSDateComponents *components1 = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:YOUR_FIRST_DATE];

// Extract time components into components2
NSDateComponents *components2 = [calendar components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit 
fromDate:YOUR_SECOND_DATE];

// Combine date and time into components3
NSDateComponents *components3 = [[NSDateComponents alloc] init];

[components3 setYear:components1.year];
[components3 setMonth:components1.month];
[components3 setDay:components1.day];    

[components3 setHour:components2.hour];
[components3 setMinute:components2.minute];
[components3 setSecond:components2.second];         

// Generate a new NSDate from components3.
NSDate *combinedDate = [calendar dateFromComponents:components3];   

// combinedDate contains both your date and time!
NSLog(@"%@", combinedDate);

Thursday, 16 August 2012

Add Minutes | Hours | Days to NSDate


NSDate *date = [NSDate date];
NSTimeInterval timeInterval = YOUR_DOUBLE_VALUE;
NSLog(@"Time Interval : %.2f", timeInterval);
date = [date dateByAddingTimeInterval:timeInterval];
NSLog(@"Date : %@",date);

For Minutes : +/-(no.of mins * 60);
For Hours : +/-(no. of hrs * 60 * 60);
For days : +/-(no. of days * 60 * 60 * 24);
+ sign for add.
- sign for subtract.
Both will work.

NSTimeInterval accepts double value.