How to combine date and time from two UIDatePickers? - iphone

I have two UIDatePickers in my app, one mode is for selecting date and other to time mode. I have fired a notification when the exact date and time is reached. I'm able to fire the reminder at correct time, but the problem is that the date is not checked. Is there any way to check the date and time at the same time??
Thanx in advance...
Edit
NSDate *date1 = [datePicker date];
NSDate *date2 = [timePicker date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
unsigned unitFlagsDate = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *dateComponents = [gregorian components:unitFlagsDate fromDate:date1];
unsigned unitFlagsTime = NSHourCalendarUnit | NSMinuteCalendarUnit ;
NSDateComponents *timeComponents = [gregorian components:unitFlagsTime fromDate:date2];
[dateComponents setHour:[timeComponents hour]];
[dateComponents setMinute:[timeComponents minute]];
NSDate *combDate = [gregorian dateFromComponents:dateComponents];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil) return;
NSDate *fireTime = combDate;
localNotif.fireDate = fireTime;
localNotif.alertBody = #"Alert!";
localNotif.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:self.datePicker.date];
NSDateComponents *timeComponents = [calendar components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:self.timePicker.date];
NSDateComponents *newComponents = [[NSDateComponents alloc]init];
newComponents.timeZone = [NSTimeZone systemTimeZone];
[newComponents setDay:[dateComponents day]];
[newComponents setMonth:[dateComponents month]];
[newComponents setYear:[dateComponents year]];
[newComponents setHour:[timeComponents hour]];
[newComponents setMinute:[timeComponents minute]];
NSDate *combDate = [calendar dateFromComponents:newComponents];
NSLog(#" \ndate : %# \ntime : %#\ncomDate : %#",self.datePicker.date,self.timePicker.date,combDate);

Swift 5 version of the accepted answer if it might help.
/// Returns `Date` from date and time.
func combine(date: Date, time: Date) -> Date? {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.day, .month, .year], from: date)
let timeComponents = calendar.dateComponents([.hour, .minute, .second], from: time)
var newComponents = DateComponents()
newComponents.timeZone = .current
newComponents.day = dateComponents.day
newComponents.month = dateComponents.month
newComponents.year = dateComponents.year
newComponents.hour = timeComponents.hour
newComponents.minute = timeComponents.minute
newComponents.second = timeComponents.second
return calendar.date(from: newComponents)
}

Try this:
Convert date into NSString and Time into NSString.
Apppend Time into date string.
Now convert that final string into NSDate
Example: (Add validations from ur side)
NSDate *date1 = [datePicker date];
NSDate *date2 = [timePicker date];
NSString *date = [NSString stringWithFormat:#"%#",date1];
NSString *time = [NSString stringWithFormat:#"%#",date2];
NSString *dateAndTime = [NSString stringWithFormat:#"%# %#",date,time];
NSDate *dateTime = [self dateFromString:dateAndTime];
- (NSDate*) dateFromString:(NSString*)aStr
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease]];
//[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss a"];
[dateFormatter setDateFormat:#"MM/dd/yyyy HH:mm:ss a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSLog(#"%#", aStr);
NSDate *aDate = [dateFormatter dateFromString:aStr];
[dateFormatter release];
return aDate;
}

Related

How to get the number of weeks in a month

Here is the problem, i'm looking for a way to get the number of weeks in a month. I already find a solution that seems to work on ios 5, but it not on io6 (number returned is not the same, one more on ios 6).
- (int)weeksOfMonth:(int)month inYear:(int)year
{
NSCalendar *cCalendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setMonth:month];
[components setYear:year];
NSRange range = [cCalendar rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:[cCalendar dateFromComponents:components]];
cCalendar = [NSCalendar currentCalendar];
[cCalendar setMinimumDaysInFirstWeek:4];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setLocale: [[NSLocale alloc] initWithLocaleIdentifier:#"fr"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSMutableSet *weeks = [[NSMutableSet alloc] init ];
for(int i = 0; i < range.length; i++)
{
NSString *temp = [NSString stringWithFormat:#"%4d-%2d- %2d",year,month,range.location+i];
NSDate *date = [dateFormatter dateFromString:temp ];
int week = [[cCalendar components: NSWeekOfYearCalendarUnit fromDate:date] weekOfYear];
[weeks addObject:[NSNumber numberWithInt:week]];
}
return [weeks count];
}
The returned value is 6 on io6 and 5 on io5.
Do you have any idea ?
EDIT : Another thing, my device (ios5) is in French and the simulator (ios6) is in English. Maybe it can change something (like the first day of week ?) ?
Try this one :
NSDate *date = [NSDate date];//since you are forming date, put it here
NSCalendar *calender = [NSCalendar currentCalendar];
NSRange weekRange = [calender rangeOfUnit:NSWeekCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
NSInteger weeksCount=weekRange.length;
NSLog(#"%d",weeksCount);
Swift 4.0:
let date = Date()
let calendar = Calendar.current
let weekRange = calendar.range(of: .weekOfMonth,
in: .month,
for: date)
let weeksCount = weekRange.count ?? 0
print(weeksCount)
Or change your method to :
- (NSInteger)weeksOfMonth:(int)month inYear:(int)year{
NSString *dateString=[NSString stringWithFormat:#"%4d/%d/1",year,month];
NSDateFormatter *dfMMddyyyy=[NSDateFormatter new];
[dfMMddyyyy setDateFormat:#"yyyy/MM/dd"];
NSDate *date=[dfMMddyyyy dateFromString:dateString];
NSCalendar *calender = [NSCalendar currentCalendar];
NSRange weekRange = [calender rangeOfUnit:NSWeekCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
NSInteger weeksCount=weekRange.length;
return weeksCount;
}
EDIT:
use this in above method
//NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calender setFirstWeekday:2]; //sunday=1, monday=2 etc
Check this approach.
-(NSArray*)getWeekDaysForDate {
int dayOfWeek = [self weekDay];
NSMutableArray *array = [NSMutableArray array];
NSDate *weekStartDate = [self offsetDay:1-dayOfWeek];
NSCalendar *calendar = [NSCalendar defaultCalendar];
NSInteger monthValue = [self month];
unsigned int weekNum = [[calendar components: NSWeekCalendarUnit
fromDate: weekStartDate] week];
NSDate * nextDate = weekStartDate, *curDate;
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay:1];
unsigned int newWeekNum;
do {
curDate = nextDate;
nextDate = [calendar dateByAddingComponents:oneDay toDate: curDate
options:0];
newWeekNum = [[calendar components: NSWeekCalendarUnit fromDate:
nextDate] week];
int monthValueForNextDate = [[calendar components: NSMonthCalendarUnit fromDate:
nextDate] month];
if(monthValue == monthValueForNextDate)
[array addObject:nextDate]];
} while (newWeekNum == weekNum);
[array sortUsingSelector:#selector(compare:)];
return array;
}
-(int)month {
NSCalendar *gregorian = [NSCalendar defaultCalendar];
NSDateComponents *components = [gregorian components:NSMonthCalendarUnit fromDate:self];
return [components month];
}
-(int)weekDay {
NSCalendar *gregorian = [NSCalendar defaultCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit fromDate:self];
return [components weekday];
}
-(NSDate *)offsetDay:(int)numDays {
NSCalendar *gregorian = [NSCalendar defaultCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:numDays];
return [gregorian dateByAddingComponents:offsetComponents
toDate:self options:0];
}
PS: NSCalendar defaultCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
Adding this method then the category of NSDate will return the weekdays of any date that lies in the same week.
Best Regards.

List days in calendar year

I am wanting to list (NSLog) all the dates of the Georgian calendar year (2013). I have managed to get the current date using the following:
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents* components = [calendar components:NSDayCalendarUnit
fromDate:currDate];
NSInteger day = [components day];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(#"%#", dateString);
How can I print out all the dates in 2013?
NSDateFormatter* dateFormatter = [NSDateFormatter new] ;
dateFormatter.dateStyle = NSDateFormatterLongStyle ;
NSDate* today = [NSDate date] ;
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] ;
NSDateComponents* thisYearComponents = [calendar components:NSYearCalendarUnit fromDate:today] ;
NSDate* firstDateInThisYear = [calendar dateFromComponents:thisYearComponents] ;
NSDateComponents* addDaysComponents = [NSDateComponents new] ;
addDaysComponents.day = 0 ;
while ( TRUE ) {
NSDate* nextDateInThisYear = [calendar dateByAddingComponents:addDaysComponents toDate:firstDateInThisYear options:0] ;
NSDateComponents* yearOfNextDateComponents = [calendar components:NSYearCalendarUnit fromDate:nextDateInThisYear] ;
if ( yearOfNextDateComponents.year == thisYearComponents.year )
NSLog(#"%#", [dateFormatter stringFromDate:nextDateInThisYear]) ;
else
break ;
addDaysComponents.day += 1 ;
}
The WWDC 2011 session 117 - Performing Calendar Calculations is a great source of information. It covers why it's better practice to, in a loop, add n days to a fixed reference date, rather than repeatedly adding 1 day to the most recently used date.
It also suggests using noon (12pm) instead of midnight (12am) for NSDates in which you don't care about the time, because Daylight Saving Time causes midnight to not exist for certain dates in certain places. But I didn't bother to do that in my example.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:#"2013-01-01"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:kCFCalendarUnitYear fromDate:date];
while ([components year] < 2014) {
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateStyle:NSDateFormatterLongStyle];
NSString *dateString = [dateFormatter1 stringFromDate:date];
NSLog(#"%#", dateString);
date = [NSDate dateWithTimeInterval:60*60*24 sinceDate:date];
components = [calendar components:kCFCalendarUnitYear fromDate:date];
}

Getting next date and previous day date

I basically want to convert a particular date (x) to the previous day date(x - 1 day) and also to the next day date (x + 1 day). I am using the following code for this :
NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)];
However I have my date (x) in NSString format, and I need to convert the NSString(myDateString) to NSDate(myDate) before applying the above code.
I have a NSString containing date in format MM-dd-yyyy.
For converting I am using the following code , but I am getting absurd values.
NSLog(#"myDateString=%#",myDateString);//output:myDateString=10-25-2012//all correct
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-yyyy"];
NSDate *myDate=[formatter dateFromString:myDateString];
NSLog(#"myDate=%#",myDate);//output:myDate=2012-10-24 18:30:00 +0000 // I only want the date to be shown // and why has the format changed
NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)];
NSLog(#"datePlusOneDay=%#",datePlusOneDay);//output:datePlusOneDay=2012-10-25 18:30:00 +0000// I only want the date to come , not time // and why has the format changed
Later again I need to convert the NSDate to NSString
NSString *curentString=[formatter stringFromDate:datePlusOneDay];
NSLog(#"curentString=%#",curentString); //output:curentString=10-26-2012
Similarly I also want to get the previous date.
Please help guys !! and ho ho MERRY CHRISTMAS !!
Do as: componets.day = 1 to obtain the next, -1 for the previous day.
NSDate *date = [NSDate date]; // your date from the server will go here.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *newDate = [calendar dateByAddingComponents:components toDate:date options:0];
NSLog(#"newDate -> %#",newDate);
The below code should get you the previous date:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-1]; // replace "-1" with "1" to get the datePlusOneDay
NSDate *dateMinusOneDay = [gregorian dateByAddingComponents:offsetComponents toDate:myDate options:0];
Merry Xmas :)
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]];
[components setHour:-[components hour]];
[components setMinute:-[components minute]];
[components setSecond:-[components second]];
NSDate *today = [cal dateByAddingComponents:components toDate:[[NSDate alloc] init] options:0]; //This variable should now be pointing at a date object that is the start of today (midnight);
[components setHour:-24];
[components setMinute:0];
[components setSecond:0];
NSDate *yesterday = [cal dateByAddingComponents:components toDate: today options:0];
Try this simple solution for previous date:-
NSDate *datePlusOneDay = [[NSDate date] dateByAddingTimeInterval:-(60 * 60 * 24)];
NSLog(#"datePlusOneDay=%#",datePlusOneDay);
Swift 5 Solution
let calendar = Calendar.current
calendar.date(byAdding: .day, value: -2, to: Date())
function for previousDay
-(void)previousDay
{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
dateString = [dateFormat stringFromDate:today];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
comps.day =-1;
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
EndingDate = [dateFormat stringFromDate:sevenDays];
}
function for next day
-(void)nextDay
{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
dateString = [dateFormat stringFromDate:today];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
comps.day =1;
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
EndingDate = [dateFormat stringFromDate:sevenDays];
}

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

get current date from [NSDate date] but set the time to 10:00 am

How can I reset the current date retrieved from [NSDate date] but then change the time to 10:00 in the morning.
As with all date manipulation you have to use NSDateComponents and NSCalendar
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
[components setHour:10];
NSDate *today10am = [calendar dateFromComponents:components];
in iOS8 Apple introduced a convenience method that saves a few lines of code:
NSDate *d = [calendar dateBySettingHour:10 minute:0 second:0 ofDate:[NSDate date] options:0];
Swift:
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()
let date10h = calendar.dateBySettingHour(10, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)!
this nsdate used different format:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"MMM dd, yyyy HH:mm"];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:#"MMM dd, yyyy"];
NSDate *parsed = [inFormat dateFromString:dateString];
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:10];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate options:0];
[comps release];
Not tested in xcode though :)
I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.
let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!
You can use this method for any minute / hour / period (aka am/pm) combination:
- (NSDate *)todayModifiedWithHours:(NSString *)hours
minutes:(NSString *)minutes
andPeriod:(NSString *)period
{
NSDate *todayModified = NSDate.date;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSMinuteCalendarUnit fromDate:todayModified];
[components setMinute:minutes.intValue];
int hour = 0;
if ([period.uppercaseString isEqualToString:#"AM"]) {
if (hours.intValue == 12) {
hour = 0;
}
else {
hour = hours.intValue;
}
}
else if ([period.uppercaseString isEqualToString:#"PM"]) {
if (hours.intValue != 12) {
hour = hours.intValue + 12;
}
else {
hour = 12;
}
}
[components setHour:hour];
todayModified = [calendar dateFromComponents:components];
return todayModified;
}
Requested Example:
NSDate *todayAt10AM = [self todayModifiedWithHours:#"10"
minutes:#"00"
andPeriod:#"am"];