Replacement of date object with “today” and “yesterday” strings in iphone - 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");
}

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

Check whether a specified date is today, yesterday, or a future date

I have one query regarding NSDate. I have a date i.e. "2011-10-04 07:36:38 +0000", and I want to check if this date is yesterday, or today or a future date.
How would I go about this?
Try this:
Note: Change the date format as per your need.
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM/dd/yyyy"];
NSDate* enteredDate = [df dateFromString:#"10/04/2011"];
NSDate * today = [NSDate date];
NSComparisonResult result = [today compare:enteredDate];
switch (result)
{
case NSOrderedAscending:
NSLog(#"Future Date");
break;
case NSOrderedDescending:
NSLog(#"Earlier Date");
break;
case NSOrderedSame:
NSLog(#"Today/Null Date Passed"); //Not sure why This is case when null/wrong date is passed
break;
}
See Apple's documentation on date calculations:
NSDate *startDate = ...;
NSDate *endDate = ...;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];
If days is between +1 and -1 then your date is a candidate for being "today". Obviously you'll need to think about how you handle hours. Presumably the easiest thing would be to set all dates to be 00:00.00 hours on the day in question (truncate the date using an approach like this), and then use those values for the calculation. That way you'd get 0 for today, -1 for yesterday, +1 for tomorrow, and any other value would likewise tell you how far things were in the future or the past.
Use any of the folowing according to ur need,
– earlierDate:
– laterDate:
– compare:
Refer this http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
-(NSString*)timeAgoFor:(NSString*)tipping_date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:tipping_date];
NSString *key = #"";
NSTimeInterval ti = [date timeIntervalSinceDate:[NSDate date]];
key = (ti > 0) ? #"Left" : #"Ago";
ti = ABS(ti);
NSDate * today = [NSDate date];
NSComparisonResult result = [today compare:date];
if (result == NSOrderedSame) {
return[NSString stringWithFormat:#"Today"];
}
else if (ti < 86400 * 2) {
return[NSString stringWithFormat:#"1 Day %#",key];
}else if (ti < 86400 * 7) {
int diff = round(ti / 60 / 60 / 24);
return[NSString stringWithFormat:#"%d Days %#", diff,key];
}else {
int diff = round(ti / (86400 * 7));
return[NSString stringWithFormat:#"%d Wks %#", diff,key];
}
}

Compare current time with fixed time 05:00:00 PM

How will I compare current time [NSDate date] with fixed time 05:00:00 PM.
That 05:00 PM is already passed or not. I just need BOOL check for this.
- (BOOL)past5pm
{
NSCalendar *gregorianCalender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [gregorianCalender components:NSHourCalendarUnit fromDate:[NSDate date]];
if([components hour] >= 17) // NSDateComponents uses the 24 hours format in which 17 is 5pm
return YES;
return NO;
}
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH.mm"];
NSDate *currentDate = [NSDate date];
NSString *curDate = [dateFormatter stringFromDate:currentDate];
if ([curDate doubleValue] >= 17.00)
{
//set your bool
}
Try this
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"hh:mm:ss a"];
NSDate* date = [NSDate date];
//Get the string date
NSString* str = [dateFormatter stringFromDate:date];
NSDate *firstDate = [dateFormatter dateFromString:#"05:00:00 PM"];
NSDate *secondDate = [dateFormatter dateFromString:str];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
NSLog(#"Time Diff - %f",timeDifference);
You can probably use plain C style code and get the difference as an integer and then decide what you need to return from the comparison function depending on wether the difference is positive or negative. You can compare minutes this way as well. Dont forget to import time.h.
time_t now = time(NULL);
struct tm oldCTime;
localtime_r(&now, &oldCTime);
int hours = oldCTime.tm_hour;
int diff = 17-hours;
NSLog(#"Time difference is: %d.", diff);

Create Event with NSDate

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

How to find last day of week in iPhone?

In my application I'm using following codes to retrieve current date and day :-
NSDate *today1 = [NSDate date]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:#"dd/MM/yyyy :EEEE"]; NSString *dateString11 = [dateFormat stringFromDate:today1];
NSLog(#"date: %#", dateString11);
//[dateFormat release];
NSCalendar *gregorian11 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
NSDateComponents *components1 = [gregorian11 components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today1];
[components1 setDay:([components1 day]-([components1 weekday]-1))];
NSDate *beginningOfWeek1 = [gregorian11 dateFromComponents:components1];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:#"dd/MM/yyyy :EEEE"];
NSString *dateString_first = [dateFormat_first stringFromDate:beginningOfWeek1];
NSLog(#"First_date: %#", dateString_first);
[components1 setDay:([components1 day]-([components1 weekday]-1) + 6)]; now =[gregorian dateFromComponents:components1]; [format setDateFormat:#"dd/MM/yyyy :EEEE"]; dateString = [format stringFromDate:now]; NSLog(#" week Last_date: %#", dateString);
but using above code I only got the current day and Date and first day of week but I need to get last day of week. But it gives the wrong output. Where am I wrong in my code and what modification is needed to get last day/date of week?
When you call setDay: you are sometimes setting it to a negative day. I don't know if setDay and/or dateFromComponents: will handle that.
To create a NSDate for a date/time that is in the past (or future) you can subtract (or add) the number of seconds that you want to go back (or forward), like this:
// convert to seconds
NSTimeInterval tmpSecs = [[NSDate date] timeIntervalSinceReferenceDate];
// Shift the date/time (in seconds) to a new date X days away:
tmpSecs += daysOffset * 86400; // 86400 seconds per day
// convert back to NSDate and return the result
return [NSDate dateWithTimeIntervalSinceReferenceDate:tmpSecs];