Create Event with NSDate - iphone

is there any way to create events for NSDate ? here is my code
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"MMMM d, yyyy"];
NSString *dateStr = [dateFormatter stringFromDate:date];
myDate.text = dateStr;
for example if date = 12 FEB ;
myDate .text = #"Mother Day";
something like this

sure it is. You have to split the date into day and month using NSDateComponents
You could write a method like this:
- (BOOL)date:(NSDate *)date isSameAsDay:(NSInteger)day andMonth:(NSInteger)month {
NSUInteger dateFlags = NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *components = [[NSCalendar currentCalendar] components:dateFlags fromDate:date];
if ([components day] == day && [components month] == month) {
return YES;
}
return NO;
}
and you would use it like this
if ([self date:[NSDate date] isSameAsDay:12 andMonth:2]) {
myDate.text = #"Mother Day";
}

This should do it:
NSDate *today = [NSDate date]; // Get ref to todays date
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
[gregorian components:(NSWeekdayOrdinalCalendarUnit | NSWeekdayCalendarUnit | NSMonthCalendarUnit) fromDate:today];
NSInteger weekday = [weekdayComponents weekday]; // Sun == 1, Mon == 2, Tue...
NSInteger weekdayOrdinal = [weekdayComponents weekdayOrdinal]; // First weekday month == 1 etc...
NSInteger month = [weekdayComponents month];
NSLog (#"%i %i %i", weekday, weekdayOrdinal, month);
// Mothers day is every second Sunday of May so weekday == 1, weekdayOrdinal == 2, month == 5
if ((weekday == 1) && (weekdayOrdinal == 2) && (month == 5)) {
NSLog (#"It's mothers day!");
}
[gregorian release];

Related

How can I make an NSDate aim for the closest future match?

Here's an example of what I want. The user may set up an alarm in my app for 1 minute in the future, so they can test it out. The time might be 19:23, so they'll set the alarm to 19:24, in which case I want it to be triggered on the next occurrence of 19:24 - in 1 minute's time.
If they set the alarm for 8am, I don't want it to set to 8am on the current day, but on the next occurrence of 8am - on following day.
How can I get it to aim for the next occurrence of the time chosen?
Assuming that the alarm time is given as "hour" and "minute", the following code
should produce the desired result:
NSDate *now = [NSDate date];
// Example values for testing:
NSUInteger alarmHour = 10;
NSUInteger alarmMinute = 5;
// Compute alarm time by replacing hour/minute of the current time
// with the given values:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit
fromDate:now];
[comp setHour:alarmHour];
[comp setMinute:alarmMinute];
NSDate *alarm = [cal dateFromComponents:comp];
// If alarm <= now ...
if ([alarm compare:now] != NSOrderedDescending) {
// ... add one day:
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay:1];
alarm = [cal dateByAddingComponents:oneDay toDate:alarm options:0];
}
More tersely, what #HotLicks suggests:
NSDate *userEnteredDate;
NSDate *now = [NSDate date];
if (now == [now laterDate:userEnteredDate]) {
NSDateComponents *components = [[NSCalendar currentCalendar] components:255 fromDate:userEnteredDate]; // 255= the important component masks or'd together
components.day += 1;
userEnteredDate = [[NSCalendar currentCalendar] dateFromComponents:components];
}
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSDateFormatter *formatter_ = [[NSDateFormatter alloc]init];
NSDate *alarmDate = [formatter dateFromString:#"enter your users alarm time-examle(2345)"];
NSDate *currentDate = [NSDate date];
[formatter setDateFormat:#"HHmm"];
NSDate *finalDate;
if ([[formatter stringFromDate:currentDate] intValue] > [[formatter stringFromDate:alarmDate] intValue]) {
[formatter setDateFormat:#"HH:mm"];
[formatter_ setDateFormat:#"dd MM yyyy"];
NSDate *date = [currentDate dateByAddingTimeInterval:60*60*24*1];
finalDate = [formatter_ dateFromString:[NSString stringWithFormat:#"%# %#",[formatter stringFromDate:alarmDate],[formatter_ stringFromDate:date]]];
}else{
finalDate = [formatter_ dateFromString:[NSString stringWithFormat:#"%# %#",[formatter stringFromDate:alarmDate],[formatter_ stringFromDate:currentDate]]];
}

Replacement of date object with “today” and “yesterday” strings in iphone

I want to return my date objects with string “today” and “yesterday” and dates in Objective C.Please all comments are welcome:
I have dates with format #"yyyy-MM-dd HH:mm:ss"] and then figures out if the date is today or yesterday and than, if it is, it returns "(Yesterday | Today | Date ) " formated string.
NSDateFormatter can do this. However this does not work with custom date formats, but in most cases when you need relative dates you are presenting them to the user and you should not use hard coded date formats in the first place.
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.timeStyle = NSDateFormatterMediumStyle;
df.dateStyle = NSDateFormatterShortStyle;
df.doesRelativeDateFormatting = YES; // this enables relative dates like yesterday, today, tomorrow...
NSLog(#"%#", [df stringFromDate:[NSDate dateWithTimeIntervalSinceNow:-48*60*60]]);
NSLog(#"%#", [df stringFromDate:[NSDate dateWithTimeIntervalSinceNow:-24*60*60]]);
NSLog(#"%#", [df stringFromDate:[NSDate date]]);
NSLog(#"%#", [df stringFromDate:[NSDate dateWithTimeIntervalSinceNow:24*60*60]]);
NSLog(#"%#", [df stringFromDate:[NSDate dateWithTimeIntervalSinceNow:48*60*60]]);
this will print:
2013-06-06 09:13:22.844 x 2[11732:c07] 6/4/13, 9:13:22 AM
2013-06-06 09:13:22.845 x 2[11732:c07] Yesterday, 9:13:22 AM
2013-06-06 09:13:22.845 x 2[11732:c07] Today, 9:13:22 AM
2013-06-06 09:13:22.846 x 2[11732:c07] Tomorrow, 9:13:22 AM
2013-06-06 09:13:22.846 x 2[11732:c07] 6/8/13, 9:13:22 AM
On a device with german locale this will print "Vorgestern" (the day before yesterday) and "Übermorgen" (the day after tomorrow) for the first and last date.
What about NSDateFormatters setDoesRelativeDateFormatting ?
Specifies whether the receiver uses phrases such as “today” and “tomorrow” for the date component.
- (void)setDoesRelativeDateFormatting:(BOOL)b
Set parameters b = YES to specify that the receiver should use relative date formatting,
otherwise NO.
Take a look: NSDateFormatter class reference
I hope this also will be usefull for you as well:
NSDate *date = somedate;
NSInteger dayDiff = (int)[date timeIntervalSinceNow] / (60*60*24);
NSDateComponents *componentsToday = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSDateComponents *componentsDate = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:somedate];
NSInteger day = [componentsToday day] - [componentsDate day];
if (dayDiff == 0) {
NSLog(#"Today");
} else if (dayDiff == -1) {
NSLog(#"Yesterday");
} else if(dayDiff > -7 && dayDiff < -1) {
NSLog(#"This week");
} else if(dayDiff > -14 && dayDiff <= -7) {
NSLog(#"Last week");
} else if(dayDiff >= -60 && dayDiff <= -30) {
NSLog(#"Last month");
} else {
NSLog(#"A long time ago");
}
Replacement of date object with “today” and “yesterday” strings in Swift.
If you want to display date with different formate then change the timeStyle and dateStyle as per you need.
var df = DateFormatter()
df.timeStyle = .medium
df.dateStyle = .short
df.doesRelativeDateFormatting = true
// this enables relative dates like yesterday, today, tomorrow...
print("\(df.string(from: Date(timeIntervalSinceNow: -48 * 60 * 60)))")
print("\(df.string(from: Date(timeIntervalSinceNow: -24 * 60 * 60)))")
print("\(df.string(from: Date()))")
print("\(df.string(from: Date(timeIntervalSinceNow: 24 * 60 * 60)))")
print("\(df.string(from: Date(timeIntervalSinceNow: 48 * 60 * 60)))")
Result:
6/4/13, 9:13:22 AM
Yesterday, 9:13:22 AM
Today, 9:13:22 AM
Tomorrow, 9:13:22 AM
6/8/13, 9:13:22 AM
NSDate *todayDate = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *today = [dateFormat stringFromDate:todayDate];
NSLog(#"today is %#",today);
NSDate *yesterdayDate = [todayDate dateByAddingTimeInterval: -86400.0];
NSString *yesterday = [dateFormat stringFromDate:yesterdayDate];
NSLog(#"yesterday was %#",yesterday);
NSString *yourDate = [NSString stringWithFormat:#"2013-06-08 12:33:28"];
if ([yourDate isEqualToString:yesterday]) {
NSLog(#"yesterday");
}
else if ([yourDate isEqualToString:today])
{
NSLog(#"today");
}
else
{
NSLog(#"the date is %#",yourDate);
}
1) take out today's and yesterday's date , then compare the the date you enter and print accordingly
NSTimeInterval interval = [dict[#"deviceTimeStamp"]doubleValue]; // set your intervals
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval]; // set your past date or create it using dateWithIntervalSince1970 method
[formatter setDateFormat:#"hh:mm a"];
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: date];
NSDate *dateee = [NSDate dateWithTimeInterval: seconds sinceDate: date];
NSDateComponents *components = [[NSCalendar currentCalendar] components:units fromDate:dateee toDate:[NSDate date] options:0];
if (components.day > 0)
{
if (components.day > 1){
[formatter setDateFormat:#"MMM dd"];
NSString *dateString = [formatter stringFromDate:date];
NSlog(#"%#",dateString);
}
else{
NSlog(#"Yesterday");
}
}
else{
NSlog(#"Today");
}

Check if current date is between two given dates [duplicate]

This question already has answers here:
How to Check if an NSDate occurs between two other NSDates
(10 answers)
Closed 9 years ago.
I want to check if current date is between two given dates. I do the following
NSDate *now = [NSDate new];
NSLog(#"Now is %#",now);
NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
[components setYear:2013];
[components setMonth:06];
[components setDay:28];
[components setHour:5];
[components setMinute:00];
NSDate *startDate1 = [myCalendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone localTimeZone];
formatter.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSLog(#"start dateeee is %#",startDate1);
NSDateComponents* components2 = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
[components2 setYear:2013];
[components2 setMonth:06];
[components2 setDay:29];
[components2 setHour:4];
[components2 setMinute:59];
NSDate *endDate1 = [myCalendar dateFromComponents:components];
NSLog(#"end date is %#",endDate1)
;
Now I have created 2 dates Startdate1 and endDate1. For to check if the current date is between those to dates I am doing this.
NSComparisonResult result1 = [now compare:startDate1];
NSComparisonResult result2 = [now compare:endDate1];
if (result2 == NSOrderedSame && result1 == NSOrderedSame ) {
NSLog(#"HELL YEAH! ");
}
But I never get a HELL YEAH ??
NOTE: I have set my iPhone datetime to a time between the start and enddate. Also here are my LOGS:
2013-06-29 11:11:48.727 Genk on stage[2205:907] Now is 2013-06-29 09:11:48 +0000
2013-06-29 11:11:48.728 Genk on stage[2205:907] start dateeee is 2013-06-28 03:00:00 +0000
2013-06-29 11:11:48.729 Genk on stage[2205:907] end date is 2013-06-28 03:00:00 +0000
Your logic is flawed. The return value NSOrderedSame means that two values compared equal. That's not what you want. Instead, you want to check if the first date comes before the current date and the second one comes after it:
if (result1 == NSOrderedAscending && result2 == NSOrderedDescending)
is what you should write.
change your code to
if (result2 == NSOrderedDescending && result1 == NSOrderedAscending ) {
NSLog(#"HELL YEAH! ");
}
This might solve your problem
Happy coding :)
NSDate * now;.....
NSDate * endDate1;......
if ([now compare: endDate1] == NSOrderedDescending) {
NSLog(#"now is later than endDate1");
} else if ([now compare: endDate1] == NSOrderedAscending) {
NSLog(#"now is earlier than endDate1");
} else {
NSLog(#"dates are the same");
}
You can use the following code.
NSTimeInterval fromTime = [startDate1 timeIntervalSinceReferenceDate];
NSTimeInterval toTime = [endDate1 timeIntervalSinceReferenceDate];
NSTimeInterval currTime = [[NSDate date] timeIntervalSinceReferenceDate];
if(currTime>fromTime && currTime<toTime)
{
//current time lies between the two dates
}
You can check this using this :
- (BOOL)yourDate:(NSDate *)date inRangeFirstDate:(NSDate *)startDate lastDate:(NSDate *)endDate {
return [date compare:startDate] == NSOrderedDescending &&
[date compare:endDate] == NSOrderedAscending;
}
If it returns YES then yourDate lies between the startDate and endDate else it returns NO.
Hope it helps you

Check if NSDate is in this week or next week

there is a way to check if an NSDate is this week or is next week?
i know that today is:
[NSDate date]
and then how i can do?
Use NSDateComponents, something like this:
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *today = [NSDate date];
NSDateComponents *todaysComponents =
[gregorian components:NSWeekCalendarUnit fromDate:date];
NSUInteger todaysWeek = [todaysComponents week];
NSDate *anotherDate = [NSDate date];
NSDateComponents *otherComponents =
[gregorian components:NSWeekCalendarUnit fromDate:anotherDate];
NSUInteger anotherWeek = [otherComponents week];
if(todaysWeek==anotherWeek){
NSLog(#"another date is this week");
}else if(todaysWeek+1==anotherWeek){
NSLog(#"another date is next week")
}
You can also use other components like month or year to be completely sure.
NOTE: Don't use timeIntervals. By using NSDateComponents you ignore the hour, minutes and seconds. I think you want that.
pass the 2 dates to this method:
- (BOOL) isSameWeekAsDate: (NSDate *) aDate andDate:(NSDate *) bDate
{
NSDateComponents *components1 = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit) fromDate:aDate];
NSDateComponents *components2 = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit) fromDate:bDate];
if ([components1 week] != [components2 week]) return NO;
//return (abs([self timeIntervalSinceDate:aDate]) < 604800); // ops, forgot to change "self" with parameter "bDate":
return (abs([bDate timeIntervalSinceDate:aDate]) < 604800);
}
EDIT:
call it with 2 dates of different years:
[components setDay:31];
[components setMonth:12];
[components setYear:2010];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date1 = [gregorian dateFromComponents:components];
// second date (SATURDAY -of the same week, other year...)
[components setDay:1];
[components setMonth:1];
[components setYear:2011];
NSDate *date2 = [gregorian dateFromComponents:components];
if ([self isSameWeekAsDate:date1 andDate:date2]) {
NSLog(#"Same Week!");
}else{
NSLog(#"OTHER WEEK!");
}
I'am adding my solution (implemented as an NSDate category), which doesn't use week, which is deprecated in iOS7, iOS8
- (NSDate *)firstDateOfWeek {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *startOfWeek;
[calendar rangeOfUnit:NSCalendarUnitWeekOfYear startDate:&startOfWeek interval:NULL forDate:self];
return startOfWeek;
}
- (BOOL)isSameWeekWithDate:(NSDate *)date {
if (ABS(self.timeIntervalSince1970 - date.timeIntervalSince1970) > (7 * 24 * 60 * 60)) {
return NO;
}
return ([[self firstDateOfWeek] timeIntervalSince1970] == [[date firstDateOfWeek] timeIntervalSince1970]);
}
- (BOOL)isThisWeek {
return [self isSameWeekWithDate:[NSDate new]];
}
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:NSWeekCalendarUnit fromDate:yourDate];
NSInteger week = [components week]; // here your have a Integer with the weeknr of yourDate
components = [cal components:NSWeekCalendarUnit fromDate:[NSDate date]];
weekToday = [components week]; // here your have a Integer with the weeknr of today
The rest you should be able to do.
It might get another brainwork when it comes to the last week in year.
Clear?
NOTE: this calculates the idea of "week" using a Sunday-Saturday concept of week.
To calculate the current day of the week use the following from here:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:dateOfInterest];
NSInteger weekday = [weekdayComponents weekday];
// weekday 1 = Sunday for Gregorian calendar
[gregorian release];
The rest should be pretty trivial. Get the current date and the date from your NSDate. Find the start and end dates using the day and the date (if today is monday then date - 1 day is the first day of the week etc). Figure out which week the date is in.
For iOS 7 and above, you have to replace NSWeekCalendarUnit with NSCalendarUnitWeekOfYear
- (NSInteger)thisW:(NSDate *)date
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todaysComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
NSUInteger todaysWeek = [todaysComponents weekOfYear];
NSDateComponents *otherComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:date];
NSUInteger datesWeek = [otherComponents weekOfYear];
//NSLog(#"Date %#",date);
if(todaysWeek==datesWeek){
//NSLog(#"Date is in this week");
return 1;
}else if(todaysWeek+1==datesWeek){
//NSLog(#"Date is in next week");
return 2;
} else {
return 0;
}
}
Forget about date components, you have to tweak lots of things (check if it's the last week of the year, check if Sunday is the beginning of the week...) and is prone to errors and spaghetti code.
This solves your issue and is extended to detect "last week", "previous weeks", "this week", "next week" and "later weeks"
-(EventWeekRange)numberOfWeeksFromTodayToEvent:(NSDate *)eventDate {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSComparisonResult comparison = [calendar compareDate:[NSDate date] toDate:eventDate toUnitGranularity:NSCalendarUnitWeekOfYear];
if (comparison == NSOrderedSame) {
return RangeThisWeek;
} else if (comparison == NSOrderedAscending) { // The event date is in the future
// Advance today's date one week to check if this new date is in the same week as the event
NSDate *todaysNextWeek = [[NSDate date]dateByAddingTimeInterval:60*60*24*7];
if ([calendar compareDate:todaysNextWeek toDate:eventDate toUnitGranularity:NSCalendarUnitWeekOfYear] == NSOrderedSame) {
return RangeNextWeek;
} else {
return RangeLater;
}
} else { // The event date is in the past
// Advance the event's date one week to check if this new date is in the same week as today
NSDate *eventsNextWeek = [eventDate dateByAddingTimeInterval:60*60*24*7];
if ([calendar compareDate:eventsNextWeek toDate:[NSDate date] toUnitGranularity:NSCalendarUnitWeekOfYear] == NSOrderedSame) {
return RangeLastWeek;
} else {
return RangeEarlier;
}
}
}

Get an array of dates in a week with reference of current date

Is there a way to get an array of dates in a week with reference to the current date?
Can you please go through this code,
NSDate *startDate = ...;
NSDate *endDate = ...;
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
int months = [comps month];
int days = [comps day];
This is a simple example from Apple. for more details
Try This its Working Fine With Me .
-(NSMutableArray *) getWeekDays{
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
[gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];
int i=(int)weekday;
int start,end;
if(i==7)
{
start=6;
end=0;
}
else if(i==6)
{
start=5;
end=1;
}
else if(i==5)
{
start=4;
end=2;
}
else if(i==4)
{
start=3;
end=3;
}
else if(i==3)
{
start=2;
end=4;
}
else if(i==2)
{
start=1;
end=5;
}
else if(i==1)
{
start=0;
end=6;
}
NSDate *cdate=[NSDate date];
NSDateFormatter *df=[[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/MM/yyyy EEEE"];
NSMutableArray *WeekDatesArr=[[NSMutableArray alloc] init];
for(start;start>0;start--)
{
NSDate *FirstDate=[cdate addTimeInterval:-(86400)*start];
NSString *str=[df stringFromDate:FirstDate];
[WeekDatesArr addObject:str];
}
for(int i=0;i<=end;i++)
{
NSDate *LastDate=[cdate addTimeInterval:(86400)*i];
NSString *str1=[df stringFromDate:LastDate];
NSLog(#"Str %# ",str1);
[WeekDatesArr addObject:str1];
}
NSLog(#"Dates Description in week %#",WeekDatesArr);
return WeekDatesArr;
}
Cheers