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.
Related
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");
}
}
This question already has an answer here:
NSDateFormatter - 1 day incorrect?
(1 answer)
Closed 7 years ago.
I try to get first date for the current month from [NSDate new]. My problem is that instead of 2015/06/01 I always receive 2015/05/31. I even try to convert string 20150601 to NSDate and I still receive 2015/05/31.
Here is my CODE (for the second element):
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyyMMdd"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
currentMonth = [dateFormatter dateFromString:#"20150601"];
The result is:
(lldb) print currentMonth
(__NSDate *) $0 = 0x79e64820 2015-05-31 21:00:00 UTC
EDIT:
Ok, I understand my mistake - I don't check correctly result of my operations. They always result in UTC.
10x, for answer and all comments. I will be more careful next time.
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
components.day = 1;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSTimeZone *zone = [NSTimeZone localTimeZone];
[formatter setTimeZone:zone];
[formatter setDateFormat:#"yyyyMMdd"];
NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];
NSString *currentMonth = [formatter stringFromDate:dayOneInCurrentMonth];
NSLog(#"%#",currentMonth);
Output
2015-06-08 14:07:30.924 NSDATEDemo[1943:39838] 20150601
Create NSDateComponents from [NSDate date], set the current day to 1 and re-create your NSDate object:
- (NSDate *) dateAtStartOfMonth
{
//Not tested!!!
NSDateComponents *comp = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
[comp setDay:1];
return [[NSCalendar currentCalendar] dateFromComponents:comp];
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I had Two Dates from date and to date. I stored two dates in NSString like string1 and string 2 respectively. Now My Problem is I want the difference of these two dates. My Date format is 04-Mar-2014 and 14-Mar-2014 and I want the result to be like 10.
You can get difference by using the code given below:-
NSString *start = #"2010-09-01";
NSString *end = #"2010-12-01";
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
[f release];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
[gregorianCalendar release];
components now holds the difference.
NSLog(#"%ld", [components day]);
Courtesy:-vikingosegundo
https://stackoverflow.com/a/4576575/1865424
Three methods you need are:
+ (NSDateFormatter *)dateFormatter
{
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YOUR_STRING_FORMAT"];
}
[NSTimeZone resetSystemTimeZone];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
return dateFormatter;
}
+ (NSDate *)dateWithString:(NSString *)dateString
{
return [[self dateFormatter] dateFromString:dateString];
}
- (NSInteger)distanceInDaysToDate:(NSDate *)date
{
NSDateComponents *components1 = [CURRENT_CALENDAR components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:self];
components1.hour = 0;
components1.minute = 0;
components1.second = 0;
NSDateComponents *components2 = [CURRENT_CALENDAR components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
components1.hour = 0;
components1.minute = 0;
components1.second = 0;
NSDate *date1 = [CURRENT_CALENDAR dateFromComponents:components1];
NSDate *date2 = [CURRENT_CALENDAR dateFromComponents:components2];
NSDateComponents *components = [CURRENT_CALENDAR components:NSDayCalendarUnit fromDate:date1 toDate:date2 options:0];
return components.day;
}
Best if you move them into NSDate category.
You Two date is
NSString* str1 = #"04-Mar-2014";
NSString* str2 = #"14-Mar-2014";
Now convert two date in to DD-MM-YYY as below
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
Now string convert into date
NSDate *date1 = [dateFormat dateFromString:str1];
NSDate *date2 = [dateFormat dateFromString:str2];
Calculation of convert between two date
NSTimeInterval distanceBetweenDates = [date2 timeIntervalSinceDate:date1];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
NSInteger day = hoursBetweenDates/ 24;
Your OUTPUT : 10
I think, according to your question, my assumption is difference between two dates. You can use this.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
NSDate *date1 = [dateFormat dateFromString:#"04-Mar-2014"];
NSDate *date2 = [dateFormat dateFromString:#"14-Mar-2014"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween / 86400;
NSLog(#"There are %d days in between the two dates.", numberOfDays);
While keeping the NSDate objects is the best solution, you can recreate NSDateobjects from the string using an NSDateFormatter with its format string set accordingly to your date format.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MMM-yy"];
[dateFormatter dateFromString:yourString];
Then you can use for example the timerIntervalSinceDate:method of NSDateand calculate the difference. Alternatively you can extract NSDateComponentsand get the difference that way.
This question already has answers here:
Comparing two NSDates and ignoring the time component
(16 answers)
Closed 9 years ago.
Essentially I have a tip of the day feature, with specific tips associated with dates, and I need a way to compare the current NSDate to the saved date for the tip, regardless of time. Obviously the tip for January 1st is relevant at 10AM and 10:30, so I can't literally compare the NSDates. Here are some of the things I've tried:
Try 1 - Doesn't work
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
// [df setDateFormat:#"yyyy-MM-dd hh:mm:ss a"];
[df setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
Try 2 - Doesn't work
NSString * zoneString = [[NSString stringWithFormat:#"%i-%i-%iT00:00:00", year, month, day] substringFromIndex:([[NSString stringWithFormat:#"%i-%i-%iT00:00:00", year, month, day] length] - 5)];
NSTimeInterval timeInterval = [[zoneString substringToIndex:3] intValue] * 3600;
timeInterval += [[zoneString substringFromIndex:3] intValue] * 60;
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:timeInterval]];
[formatter setDateFormat:#"yyyy'-'MM'-'dd' 'HH':'mm':'ss ZZZ"];
NSLog(#"%#", [formatter stringFromDate:myDate]);
Try 3 - Doesn't work
NSDate *date = [NSDate date];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date interval:NULL forDate:date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
if ([[dateFormat stringFromDate:date] isEqualToString:[dateFormat stringFromDate:tipDate]])
As a rule of thumb, when you compare or manipulate NSDates, the right tool for the job is usually a combination of NSCalendar and NSDateComponents.
Use NSDateFormatter only when you need to format and display a NSDate.
With this in mind, NSDateComponents is the way to go, since you want to compare a subset of components from the two dates.
Create two NSDateComponents instances and compare them.
Example:
- (BOOL)isToday:(NSDate *)date {
NSDateComponents *todayComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
fromDate:[NSDate date]];
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
fromDate:date];
return [dateComponents isEqual:todayComponents];
}
This question already has answers here:
How can I compare two dates, return a number of days
(4 answers)
Calculating the number of days between two dates in Objective-C
(8 answers)
Closed 9 years ago.
I'm trying to make a label that says how many days left till event. I want to calculate the difference between todays date and the events date. I'm using this code and its giving me -4600. It works fine till I use todays date.
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd"];
NSDate *startDate = [NSDate date];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
return components.day;
return components.day;
By default [NSDate date] return date in like 2013-08-06 08:50:25 +0000
and you have set your formatter to yyyy-MM-dd this, so you have to convert your startDate to yyyy-MM-dd this form..
Try this
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-ddHH:mm:ss ZZZ"];
NSDate *startDate = [NSDate date];
NSLog(#"%#",startDate);
NSDate *endDate = [f dateFromString:end];
NSLog(#"%#",endDate);
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
return components.day;