Date conversion in iOS [closed] - ios

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have to compare date (coming from server) with today's date. The date from server is in different format (that is, date format may be 2015-09-08 or 2015-09-08T11:30:00+0530)
How can we compare these different date format with today's date in iOS (Objective-C).

Actually, there is no matter if you want to compare 2 dates in different formats, the problem is to compare date values you have to ensure
1. They are converted to the same timezone.
2. Use - (NSComparisonResult)compare:(NSDate *)anotherDate method
In addition, if you want to convert your date string response from HE to NSDate, you can do as below
+ (NSDate *)dateFromDateString:(NSString *)dateString withFormat:(NSString *)format {
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = format;
return [formatter dateFromString:dateString];
}
Moreover, in term of comparing 2 dates in specific components (such as year, month, day and without hour, min or second) you have to use NSDateComponents
- (BOOL)date:(NSDate *)aDate isEqualToDateIgnoringTime:(NSDate *) anotherDate
{
NSCalendarUnit unitFlags = (NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond);
NSDateComponents *components1 = [[NSCalendar currentCalendar] components:unitFlags fromDate:aDate];
NSDateComponents *components2 = [[NSCalendar currentCalendar] components:unitFlags fromDate:anotherDate];
return ((components1.year == components2.year) && (components1.month == components2.month) && (components1.day == components2.day));
}

try with this
-(void)dateFormateTest{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-MM-dd HH:mm:ss Z";
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone defaultTimeZone]];
[NSTimeZone resetSystemTimeZone];
NSDate *date = [formatter dateFromString:#"2015-10-06 12:39:12"];
NSLog(#"date: %#",date);
NSComparisonResult result = [date compare:[NSDate date]];
if (result == NSOrderedDescending) {
NSLog(#"Past");
}else if (result == NSOrderedDescending) {
NSLog(#"future");
}
}

Related

How to check current Date is in between two dates or not In IOS

I am trying to find out whether current date is in between two given dates or not.First I coverted the two date into current date format i.e;2014-10-02 06:45:37 +0000
NSComparisonResult result,restult2;
NSString *startDateStr=#"10/04/2014 06:03 AM";
NSDateFormatter *startdf=[[NSDateFormatter alloc] init];
[startdf setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *startDate12=[startdf dateFromString:startDateStr];
NSString *startStr=[startdf stringFromDate:startDate12];
[startdf setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSDate *startDate1=[startdf dateFromString:startStr]; //here startDate1 is nil
NSString *endDateStr=#"10/07/2014 03:03 AM";
NSDateFormatter *enddf=[[NSDateFormatter alloc] init];
[enddf setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *endDate12=[enddf dateFromString:endDateStr];
NSString *endStr=[enddf stringFromDate:endDate12];
[enddf setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSDate *endDate1=[startdf dateFromString:endStr]; //here endDate1 is nil
NSDate *date = [NSDate date];
BOOL isBetween=[MyViewController date:date isBetweenDate:startDate1 andDate:endDate1];
if (isBetween)
{
NSLog(#"#####YES");
}
+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
if ([date compare:beginDate] == NSOrderedAscending)
return NO;
if ([date compare:endDate] == NSOrderedDescending)
return NO;
return YES;
}
Please give any suggestions where I am going wrong.
Thanks in Advance...!
You are doing stuff in your code that is pretty much not doing anything. An NSDate object has no format. It has no time zone. It has no months, days, years. It is merely a point in time. When you then convert that date to a string you need to provide a format (which is what NSDateFormatter is for).
Change your code to something like this...
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSString *startDateStr = #"10/04/2014 06:03 AM";
NSDate *startDate = [dateFormatter dateFromString:startDateStr];
NSString *endDateStr = #"10/07/2014 03:03 AM";
NSDate *endDate = [dateFormatter dateFromString:endDateStr];
NSDate *date = [NSDate date];
// use a function name that matches the convention...
if ([MyViewController isDate:date betweenStartDate:startDate andEndDate:endDate])
{
NSLog(#"#####YES");
}
I think your function should be fine. Just don't mess around with the dates. Once you have them stop there and use them.
Obtain NSDate from your string and compare.
NSDate doesnt contain any format. It is just number of seconds. So you dont need to reconvert it multiple times, its error prone.
Also double check that dateFromString: method doesnt return nil.
To verify, whether a date falls into defined date range, you can use compare method or review the following code:
NSDate *now = [NSDate date];
NSDate *yesterday = [now dateByAddingTimeInterval:-1*24*60*60];
NSDate *tomorrow = [now dateByAddingTimeInterval:+1*24*60*60];
//first condition
if([now compare:yesterday] == NSOrderedDescending && [now compare:tomorrow] == NSOrderedAscending)
NSLog(#"now > yesterday and now < tomorrow");
else
NSLog(#"now is outside yesterday and tomorrow");
NSDate *weekAgo = [now dateByAddingTimeInterval:-7*24*60*60];
//second condition
if([weekAgo compare:yesterday] == NSOrderedDescending && [weekAgo compare:tomorrow] == NSOrderedAscending)
NSLog(#"weekAgo > yesterday and weekAgo < tomorrow");
else
NSLog(#"weekAgo is outside yesterday and tomorrow");
First condition results to
2014-10-02 14:45:21.791 dateTest[95595:8857503] now > yesterday and now < tomorrow
Second condition results to
2014-10-02 14:45:24.425 dateTest[95595:8857503] weekAgo is outside yesterday and tomorrow
convert both dates in milliseconds
long firstDate = [#(floor([startDate1 timeIntervalSince1970] * 1000)) longLongValue];
long secondDate = [#(floor([endDate1 timeIntervalSince1970] * 1000)) longLongValue];
and then covert also the date you want to check like this and check if that value is bigger than firstDate and smaller than `secondDate'

NSDate gives wrong year

I am trying to work with NSDate and it is not working for me, I am so confused right now. So the basic thing I want works, but it needs to be the day of today and not from the year 2000.
So what I want is that the Date should be the date of today with the hours that are in my string bU and eU and not the date from the year 2000 with the hours of my string.
Here is a piece of my code:
NSDate *localNotDate;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone localTimeZone]];
[df setDateFormat:#"HH:mm"];
NSDate *bU = [df dateFromString:[[[self alarmArray] objectAtIndex:arrayInt] beginUur]]; // This is a 24:00 format string
NSDate *eU = [df dateFromString:[[[self alarmArray] objectAtIndex:arrayInt] eindUur]]; // This is a 24:00 format string
if (intForInsideForLoop == 0) { // Setup NSDate on first loop.
localNotDate = bU; // This gives the date 2000-01-01 08:24
}
if (intForInsideForLoop < timesOnDay) {
localNotDate = [localNotDate dateByAddingTimeInterval:(interval * 60)]; // Adds minutes to the date of today.
NSDateFormatter *dtest = [[NSDateFormatter alloc] init];
[dtest setTimeZone:[NSTimeZone localTimeZone]];
[dtest setDateFormat:#"yyyy-MM-dd HH:mm"];
NSLog(#"%#", [dtest stringFromDate:localNotDate]); // This gives the date 2000-01-01 08:24. it should be like It's Today thursday so 2014-05-08 08:24
}
I have found the answer to my problem with the method Martin has given from the post. This method converts an "Time" string like (18:00) to the date of today at 18:00.
Here it is:
- (NSDate *)todaysDateFromString:(NSString *)time
{
// Split hour/minute into separate strings:
NSArray *array = [time componentsSeparatedByString:#":"];
// Get year/month/day from today:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
// Set hour/minute from the given input:
[comp setHour:[array[0] integerValue]];
[comp setMinute:[array[1] integerValue]];
return [cal dateFromComponents:comp];
}

How do I accommodate opening and closing dates NSDate comparator on separate days?

Comparing dates is quite complex. I have an app that is comparing opening and closing dates for stores and it works great for times in the same day, i.e. opening a 8am and closing at 5pm the same day.
Here is the code that compares the time:
if ([self timeCompare:openDate until:closeDate withNow:now]) {
NSLog(#"TIMECOMPARATOR = timeCompare>OPEN");
status = YES;
} else {
NSLog(#"TIMECOMPARATOR = timeCompare>CLOSED");
status = NO;
}
return status;
This calls the following method:
+(BOOL)timeCompare:(NSDate*)date1 until:(NSDate*)date2 withNow:(NSDate*)now{
NSLog(#"TIMECOMPARE = open:%# now:%# close:%#", date1, now, date2);
return ([date1 compare:now] == NSOrderedAscending && [date2 compare:now] == NSOrderedDescending);
}
The problem comes when the closing time is "assumed" by a person but of course not by a computer, to close at the next day, such as 7am to 2am. I obviously mean the next day. How do I accommodate for this to signal the computer to be the next day?
Compare the date's unix time. It will be accurate regardless of date as it is constantly increasing.
First you have to convert the strings "7:00 AM", "10:00 PM" to a NSDate from the current day. This can be done e.g. with the following method:
- (NSDate *)todaysDateFromAMPMString:(NSString *)time
{
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]];
// Get year-month-day for today:
[fmt setDateFormat:#"yyyy-MM-dd "];
NSString *todayString = [fmt stringFromDate:[NSDate date]];
// Append the given time:
NSString *todaysTime = [todayString stringByAppendingString:time];
// Convert date+time string back to NSDate:
[fmt setDateFormat:#"yyyy-MM-dd h:mma"];
NSDate *date = [fmt dateFromString:todaysTime];
return date;
}
Then you can proceed as in https://stackoverflow.com/a/20441330/1187415:
// Some example values:
NSString *strOpenTime = #"10:00 PM";
NSString *strCloseTime = #"2:00 AM";
NSDate *openTime = [self todaysDateFromAMPMString:strOpenTime];
NSDate *closeTime = [self todaysDateFromAMPMString:strCloseTime];
if ([closeTime compare:openTime] != NSOrderedDescending) {
// closeTime is less than or equal to openTime, so add one day:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [[NSDateComponents alloc] init];
[comp setDay:1];
closeTime = [cal dateByAddingComponents:comp toDate:closeTime options:0];
}
NSDate *now = [NSDate date];
if ([now compare:openTime] != NSOrderedAscending &&
[now compare:closeTime] != NSOrderedDescending) {
// Shop is OPEN
} else {
// Shop is CLOSED
}
This is an app design question, not a coding question. You need to define a clear vocabulary for the user to communicate what they mean. I would suggest adding a UISwitch to the screen, with 2 positions on it: "Today" and "Tomorrow". You can add some program logic that takes a guess as to times where you think the user is talking about a date tomorrow, and set the default switch to the "tomorrow" state in that case, but the user should be able to tell you what they mean.
How about you just add a check whether all the three NSDate are having the same date (DDMMYYYY) value?

I want to get today's date without time [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Currently what I am doing is I am comparing some date say oldDate with today's date
NSDate *dt = [NSDate date];
NSComparisonResult result = [oldDate compare:dt];
if (result == NSOrderedAscending)
{
// do something
}
dt gives me today's date with time also. But I want just date and no time. How can I achieve it ?
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd/MM/YYYY"];
NSString *dateString=[dateFormatter stringFromDate:[NSDate date]];
To take care about timezones and everything you could do something like this:
- (NSInteger)day {
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit fromDate:self];
return [components day];
}
- (NSInteger)month {
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit fromDate:self];
return [components month];
}
- (NSInteger)year {
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:self];
return [components year];
}
Of course you can put it all together in one function just remember to alter components accordingly.
Caveat:
If you want something to show to the user, use one of the other answers with NSDateFormatter.
You need to use a date formatter to correctly output the date and/or time for an NSDate object.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
Setting the different NSDateFormatterStyle types will yield more or less information as required, i.e.: "Tuesday, 1st January 2013", or "01/02/2013".
Here you go:
NSDate *date = [NSDate Date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
timeFormatter.dateFormat = #"HH:mm:ss";
NSString *timeString = [timeFormatter stringFromDate:date];
Now the string timeString contains the current time in HH:mm:ss format, i.e. 11:26:59
Whoops Misread the question! this is for time only for date see other answers - might as well leave this here also.

How to compare current date to previous date in iphone?

I would like to compare the current date with another date, and if that is date is earlier than the current date, then I should stop the next action. How can I do this?
I have todays date in yyyy-MM-dd format. I need to check this condition
if([displaydate text]<currentdate)
{
//stop next action
}
Here if displaydate is less than todays date then it has to enter that condition.
NSDate *today = [NSDate date]; // it will give you current date
NSDate *newDate = [dateFormatter dateWithString:#"xxxxxx"]; // your date
NSComparisonResult result;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
result = [today compare:newDate]; // comparing two dates
if(result==NSOrderedAscending)
NSLog(#"today is less");
else if(result==NSOrderedDescending)
NSLog(#"newDate is less");
else
NSLog(#"Both dates are same");
got your solution from this answer How to compare two dates in Objective-C
Alternative to #NNitin Gohel's answer.
Compare using NSTimeInterval ie NSDate timeIntervalSince1970:
NSTimeInterval *todayTimeInterval = [[NSDate date] timeIntervalSince1970];
NSTimeInterval *previousTimeInterval = [previousdate timeIntervalSince1970];
if(previousTimeInterval < todayTimeInterval)
//prevous date is less than today
else if (previousTimeInterval == todayTimeInterval)
//both date are equal
else
//prevous date is greater than today
You can have a closer look at this Tutorial about NSDateFormatter and when you have your NSDate object you can compare it to another NSDate and get an NSTimeInterval which is the difference in seconds.
NSDate *nowDate = [NSDate date];
NSTimeInterval interval = [nowDate timeIntervalSinceDate:pastDate];
Some methods of NSDate class are:
isEarlierThanDate. // using this method you can find out the date is previous or not..
isLaterThanDate
minutesAfterDate.
minutesBeforeDate. etc..
also see this link with many methods of NSDate in iPhone SDK..
how-to-real-world-dates-with-the-iphone-sdk
Update
//Current Date
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
use this bellow method for convert NSString date to NSDate format just paste this method in your.m file
- (NSDate *)convertStringToDate:(NSString *) date {
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd"];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", date);
date = [date stringByReplacingOccurrencesOfString:#"+0000" withString:#""];
nowDate = [formatter dateFromString:date];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", nowDate);
return nowDate;
}
after that when you want to use it just use like bellow..
NSDate *tempDate2 = [self convertStringToDate:yourStringDate];
and then try to compare like this..
if (tempDate2 > nowDate)

Resources