Comparing NSDates to check if today falls in between - objective-c

thanks to you guys I have successfully converted my array of strings to NSDates. Now I'm trying to check if today's date falls in between my 2 dates (namely fromDate and toDate). I've seen the following questions but failed to implement them in my code. Be great I can have any other method or help on using the solutions given by the users.
NSDate between two given NSDates
How to Check if an NSDate occurs between two other NSDates
How can I check if an NSDate falls in between two other NSDates in an NSMutableArray
This is what I currently have:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd"];
NSTimeZone *tz = [NSTimeZone localTimeZone];
[format setTimeZone:tz];
NSDate *now = [[NSDate alloc] init];
NSString *todaysDate = [format stringFromDate:now];
NSLog(#"todaysDate: %#", todaysDate);
//converting string - date
int size = [appDelegate.ALLevents count];
for (NSUInteger i = 0; i < size; i++) {
Event *aEvent = [appDelegate.ALLevents objectAtIndex:i];
//Convert fromDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *fromDate = [dateFormatter dateFromString:aEvent.fromDate];
[dateFormatter setTimeZone:tz];
NSLog(#"fromDate: %#", fromDate);
//Convert toDate
NSDate *toDate = [dateFormatter dateFromString:aEvent.toDate];
NSLog(#"toDate: %#", toDate);
[dateFormatter release];
//Compare if today falls in between
//codes here
}

Do the following,
NSTimeInterval fromTime = [fromDate timeIntervalSinceReferenceDate];
NSTimeInterval toTime = [toDate timeIntervalSinceReferenceDate];
NSTimeInterval currTime = [[NSDate date] timeIntervalSinceReferenceDate];
NSTimeInterval is basically a double type so you can compare that if currTime is greater than one and less than the other than the date falls between those two NSDates.

Related

How to send NSDate with a certain date format as NSNumber? i.e convert NSDate to NSDate with another format?

I have two user selected dates: startDate and endDate. They are NSDate instances and I have to send them as parameters as NSNumbers. How can I convert them to NSNumber with seconds?
Use below code :
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
// set format however you want
[formatter setDateFormat:#"ddMMyyyy"];
NSDate *date = [NSDate date];
NSString *string = [formatter stringFromDate:date];
NSNumber *num1 = #([string intValue]);
NSLog(#"%#",num1);
1) First, get the date in MM/dd/yyyy format:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy"];
2) get string date and remove '/' from it:
NString *string = [formatter stringFromDate:date];
NString *finalStr = [string stringByReplacingOccurrencesOfString:#"/" withString:#""];
3) Use NSNumberFormatter from converting NSString to NSNumber:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString: finalStr];
Hope, this is what you want!
If you mean a timestamp format
NSDate *date = [NSDate date];
NSTimeInterval ti = [date timeIntervalSince1970];
How to convert NSDate into Unix timestamp in Objective C/iPhone?
Thanks,

How to convert Nstring to NSDate?

i want to convert nsstring to nsdate
i have string have this value
08:00:00
i want to convert it so i wrote this code
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [formatter dateFromString:_startTime];
NSLog(#"%#",startDate);
_startTime have this value = 08:00:00
but startDate after i display it , it had this value
2000-01-01 06:00:00 +0000
Update I wrote this code
NSString *dateString = _startTime;
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [[NSDate alloc] init];
// voila!
startDate = [formatter dateFromString:dateString];
NSLog(#"%#",startDate);
i want the output be 08:00:00
You can't have NSDate without a date !
if you want to access the time from an NSDate you'll need to use NSDateComponents (or NSTimeInterval).
To access the time from your NSDate using NSDateComponents :
NSString *startTime = #"08:00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [formatter dateFromString:startTime];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:startDate];
NSLog(#"%d:%d:%d", [components hour], [components minute], [components second]);
I don't get what's the purpose of changing the string _startTime, do you want to compare dates ?
Edit :
NSString *startTime = #"08:00:00";
NSString *endTime = #"23:00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [formatter dateFromString:startTime];
NSDate *endDate = [formatter dateFromString:endTime];
NSTimeInterval difference = [endDate timeIntervalSinceDate:startDate];
NSInteger temp = difference;
NSDate* newDate = [[NSDate alloc] init];
for (int i = 0; (i < difference && [newDate compare:startDate] == NSOrderedDescending); ++i)
{
newDate = [startDate dateByAddingTimeInterval:(temp - i*60*10)];
NSLog(#"%#",newDate);
}
run this and use NSDateComponents to log what you want !
Use this code i think this one help you..
NSString *dateStr = #"08:00:00";
NSDateFormatter *datFormatter = [[NSDateFormatter alloc] init];
[datFormatter setDateFormat:#"HH:mm:ss"];
NSDate* mydate = [datFormatter dateFromString:dateStr];
NSLog(#"date: %#", [datFormatter stringFromDate:mydate]);
i think this is what you really want...

How to get day of month in number format?

What I'm looking for is the day of the month, example 2, 5, 30 or 31. In integer form, and not a string. I'm not looking for a programmed date, but today's date in whatever local they are in.
All the above answers are bad ways to accomplish this. This is the right way:
NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSDayCalendarUnit fromDate:date];
NSInteger day = components.day;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"d"];
NSInteger day = [[dateFormat stringFromDate:[NSDate date]] intValue];
Start with an NSDate then run it through an NSDateFormatter.
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html
Here is something that may work :
NSDate *theDate;
// Set theDate to the date you want
// For example, theDate = [NSDate date]; to get today's date
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"d";
NSString *theDayString = [formatter stringFromDate:theDate];
int theDay = theDayString.intValue;
NSLog (#"%d", theDay);
theDay contains the value you're looking for !

NSDate formatting it to include Date and Time

I have two strings.
NSString *dateof = #"Mon May 21";
NSString *timeof = #"01.00 pm from 11.50 pm"; // 01.00 pm is the start time and 11.50 pm is the end time
I need to save these as NSDates, in the format , so that it will be 2012-05-21 13:00:00 +0000.
My approach so far has been:
NSDate *currentTime = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents
*currentDateComps = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:currentTime];
NSString *startDateStringWithYear = [NSString stringWithFormat:#"%# %d", startDateString, currentDateComps.year];
NSString *endDateStringWithYear = [NSString stringWithFormat:#"%# %d", endDateString, currentDateComps.year];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEE MM dd yyyy"];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *startDate = [formatter dateFromString:startDateStringWithYear];
NSArray *timeDurationStringWords = [timeof componentsSeparatedByString:#" "];
// Calculate NSDate's for the start time for today:
NSString *startTimeString = [timeDurationStringWords objectAtIndex:0];
currentDateComps.hour = [[startTimeString substringToIndex:2] intValue];
currentDateComps.minute = [[startTimeString substringFromIndex:3] intValue];
if ([[timeDurationStringWords objectAtIndex:1] isEqualToString:#"pm"])
{
currentDateComps.hour += 12;
}
NSDate *startTime = [cal dateFromComponents:currentDateComps];
When I debug the code, startTime prints as 2012-05-29 07:30:00 +0000 which is incorrect (both the day and time are incorrect). I think this is because of the GMT time.
I need the date and time to be 2012-05-21 13:00:00 +0000.
This will do it. As far as the local/GMT, this will give you a NSDate that contains the local time but the debugger will show always show it in GMT. You will need to format it (using a NSDateFormatter) into the format that you want if you are going to show it to the user, in which case it will be in local time.
NSString *dateof = #"Mon May 21";
NSString *timeof = #"01.00 pm from 11.50 pm";
NSDate *today = [NSDate date];
// Start time will be array index 0, end time will be index 1:
NSArray *times = [timeof componentsSeparatedByString:#" from "];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *yearComp = [cal components:NSYearCalendarUnit fromDate:today];
// Append the year and the time to the dateof string to get a string like #"Mon May 21 2012 01.00 pm":
NSString *start = [dateof stringByAppendingFormat:#" %d %#", yearComp.year, [times objectAtIndex:0]];
NSString *end = [dateof stringByAppendingFormat:#" %d %#", yearComp.year, [times objectAtIndex:1]];
// Make a date formatter that recognizes the above date/time:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEE MMM dd yyyy hh.mm a"];
// Convert the strings to dates:
NSDate *startDate = [formatter dateFromString:start];
NSDate *endDate = [formatter dateFromString:end];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd 'at' HH:mm"];
NSString *str = [formatter stringFromDate:[NSDate date]];
NSLog(#"str=%#",str);
NSDate *dt = [NSDate date];
dt = [formatter dateFromString:str];
NSLog(#"dt=%#",dt);
Output:
str=2012-05-29 at 10:36
dt=2012-05-29 05:06:00 +0000

Converting a string to an NSDate

How is it possible to convert a string to an NSDate on iOS?
NSString *dateStr = #"20100223";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
// Convert date object to desired output format
[dateFormat setDateFormat:#"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
[dateFormat release];
Hope this will help you.
You'll want to take a look at NSDateFormatter. Determine the format of the date string and then use dateFromString: to convert the string to an NSDate object.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/YYYY"];
NSDate *date = [dateFormat dateFromString:dateStr];
list = [self getYear:date];
- (NSMutableArray *)getYear:(NSDate*)date
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
int year = [components year];
int month = [components month];
int day = [components day];
NSLog(#"%d",year);
NSMutableDictionary *dateDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:#"%d", day], #"day", [NSString stringWithFormat:#"%d", month], #"month", [NSString stringWithFormat:#"%d", year], #"year", nil];
return dateDict;
}
My working version in Swift
func dateFor(timeStamp: String) -> NSDate
{
let formater = NSDateFormatter()
formater.dateFormat = "HH:mm:ss:SSS - MMM dd, yyyy"
return formater.dateFromString(timeStamp)!
}
func timeStampFor(date: NSDate) -> String
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm:ss:SSS - MMM dd, yyyy"
return dateFormatter.stringFromDate(date)
}
A simple approach even if you have sqlite DB:
// NSTimeInterval is basically typedef of double so you can receive it as double also.
NSTimeInterval *current = [[NSDate date] timeIntervalSince1970];
[DB addToDB:current];
//retrieve the date from DB
NSDate *retrievedDateItem = [[NSDate alloc] initWithTimeIntervalSince1970:[getDBValueAsDouble]]; //convert it from double (NSTimeInterval) to NSDate
// Set the style
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
// Converted to string
NSString *convertedDate = [dateFormatter stringFromDate:retrievedDateItem];
The output for this example:
Aug 3, 2015, 12:27:50 PM
+(NSDate*)str2date:(NSString*)dateStr{
if ([dateStr isKindOfClass:[NSDate class]]) {
return (NSDate*)dateStr;
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:dateStr];
return date;
}