How to get current year first date in iphone programmatically - iphone

Am working in iphone application, Now i want to get current year and current month first date from current date.
For (e.x: First date of year : 2013/01/01)
And (e.x first date of month is: 2013/12/01)
Please help me to out of this issue. Thanks.

// This is your currentDate
NSDate *today = [NSDate date];
// NSDateFormatter to separate the Year and Month from currentDate
NSDateFormatter *df = [[NSDateFormatter alloc] init]
[df setDateFormat:#"yyyy"];
NSInteger currentYear = [[df stringFromDate:today] integerValue];
NSString *currentYearFirstDate = [NSString stringWithFormat:#"%d/01/01", currentYear];
[df setDateFormat:#"MM"];
NSInteger currentMonth = [[df stringFromDate:today] integerValue];
NSString *currentMonthFirstDate = [NSString stringWithFormat:#"%d/%d/01", currentYear, currentMonth];
// You can get date object from above string via using below date format
[df setDateFormat:#"yyyy/MM/dd"];

NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
[components setDay:1];
self.currentDate = [calendar dateFromComponents:components];
int m = components.month;
int y = components.year;
int d = components.day;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy MM dd"];
NSDate *firstDateOfMonth = [df dateFromString:[NSString stringWithFormat:#"%d %d 01",y,m]];
NSDate *firstDateOfYear = [df dateFromString:[NSString stringWithFormat:#"%d 01 01",y]];

Related

NSDateFormatter not working to set setTimeZone

I am trying to know the difference between two dates (Including days,hours,minutes and seconds). For that I am using below code, but It's not working.
+ (void)UpdateTableViewCellWithNSTimer:(NSString *)gameTime :(UIView *)inputView{
NSDate *now = [NSDate date];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setLocale:[NSLocale systemLocale]];
[outputFormatter setAMSymbol:#"AM"];
[outputFormatter setPMSymbol:#"PM"];
[outputFormatter setTimeZone:[NSTimeZone localTimeZone]];
[outputFormatter setDateFormat:#"mm/dd/yyyy hh:mm a"];
NSDate *gameDate = [outputFormatter dateFromString:gameTime];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:gameDate toDate:now options:0];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger seconds = [components second];
NSInteger minutes = [components minute];
UITableView *dynamicTable = (UITableView *)[inputView viewWithTag:55];
NSIndexPath *cellIndexPath = [NSIndexPath indexPathForRow:4 inSection:0];
UITableViewCell *currentCell = [dynamicTable cellForRowAtIndexPath:cellIndexPath];
NSString *challengeStartsIn=[NSString stringWithFormat:#"%01ddays:%02dhrs:%02dmins:%02dsec",abs(days),abs(hours), abs(minutes), abs(seconds)];
NSString *Mystring =[NSString stringWithFormat:#"%# %#", #"ChallengeStartsIn", challengeStartsIn];
currentCell.textLabel.text = Mystring;
}
**Game and now dates on logs are:**
2013-05-18 11:36:42.609 FPPresent[2213:5203] gametime value=05/19/2013 5:30 AM
2013-05-18 11:36:42.610 FPPresent[2213:5203] now=2013-05-18 06:06:42 +0000
After using outputformatter:
gametime value =2013-01-19 00:00:00 +0000(It should be 2013-01-19 05:30:00 +0000 )
now=2013-05-18 06:10:07 +0000(should be : 2013-05-18 11:40:07 +0000)
The game date and now date should in localTimeZone. But, even I try to set
[outputFormatter setTimeZone:[NSTimeZone localTimeZone]];
My data format is showing (Exactly 5.30 hours different, our local time zone is GMT+5.30)
Please let me know where I am going wrong
[NSDate date] is taking default timezone as GMT. so, I am unable to set my local timezone to date.
While knowing the difference between GMT OFFset to local , I am able to get the difference between two dates sucessfully.
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setAMSymbol:#"AM"];
[outputFormatter setPMSymbol:#"PM"];
[outputFormatter setLocale:[NSLocale currentLocale]];
[outputFormatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *gameDate = [outputFormatter dateFromString:gameTime];
NSDate* gameDestinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:gameDate];
// NSLog(#"gameDate=%#",gameDate);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:destinationDate toDate:gameDestinationDate options:0];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger seconds = [components second];
NSInteger minutes = [components minute];
return ([NSString stringWithFormat:#"%01ddays:%02dhrs:%02dmins:%02dsec",abs(days),abs(hours), abs(minutes), abs(seconds)]);
Are you setting the timeZone for the output formatter and along with that are you adding the time difference to the output date?? Because, there is not need to add the time difference as setting timezone for both dateFormatters will automatically take care of the time difference between the time zones.

List days in calendar year

I am wanting to list (NSLog) all the dates of the Georgian calendar year (2013). I have managed to get the current date using the following:
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents* components = [calendar components:NSDayCalendarUnit
fromDate:currDate];
NSInteger day = [components day];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(#"%#", dateString);
How can I print out all the dates in 2013?
NSDateFormatter* dateFormatter = [NSDateFormatter new] ;
dateFormatter.dateStyle = NSDateFormatterLongStyle ;
NSDate* today = [NSDate date] ;
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] ;
NSDateComponents* thisYearComponents = [calendar components:NSYearCalendarUnit fromDate:today] ;
NSDate* firstDateInThisYear = [calendar dateFromComponents:thisYearComponents] ;
NSDateComponents* addDaysComponents = [NSDateComponents new] ;
addDaysComponents.day = 0 ;
while ( TRUE ) {
NSDate* nextDateInThisYear = [calendar dateByAddingComponents:addDaysComponents toDate:firstDateInThisYear options:0] ;
NSDateComponents* yearOfNextDateComponents = [calendar components:NSYearCalendarUnit fromDate:nextDateInThisYear] ;
if ( yearOfNextDateComponents.year == thisYearComponents.year )
NSLog(#"%#", [dateFormatter stringFromDate:nextDateInThisYear]) ;
else
break ;
addDaysComponents.day += 1 ;
}
The WWDC 2011 session 117 - Performing Calendar Calculations is a great source of information. It covers why it's better practice to, in a loop, add n days to a fixed reference date, rather than repeatedly adding 1 day to the most recently used date.
It also suggests using noon (12pm) instead of midnight (12am) for NSDates in which you don't care about the time, because Daylight Saving Time causes midnight to not exist for certain dates in certain places. But I didn't bother to do that in my example.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:#"2013-01-01"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:kCFCalendarUnitYear fromDate:date];
while ([components year] < 2014) {
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateStyle:NSDateFormatterLongStyle];
NSString *dateString = [dateFormatter1 stringFromDate:date];
NSLog(#"%#", dateString);
date = [NSDate dateWithTimeInterval:60*60*24 sinceDate:date];
components = [calendar components:kCFCalendarUnitYear fromDate:date];
}

Issue with calculating difference between two dates

I need to calculate difference between two days in minutes.
NSDate *now = [[NSDate alloc] init];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
[outputFormatter setDateFormat:#"dd/MM/yyyy hh:mm:ss a"];
NSString* dateStringFromDatabase = #"01/01/1900 11:00:00 AM";
NSDate* dateFromString = [outputFormatter dateFromString:dateStringFromDatabase];
NSString* a = [outputFormatter stringFromDate:now];
NSDate* b = [outputFormatter dateFromString:a];
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:dateFromString
toDate:b options:0];
int hours = [components hour];
int minutes = [components minute];
self.lblResult.text = [NSString stringWithFormat:#"%i:%i", hours, minutes];
But I have the following issues:
For current hours I get:
2012-10-21 07:37:09 +0000 // wrong it's two hours late
When I try to cast #"01/01/1900 11:00:00 AM" to NSDate I get
1900-01-01 10:00:00 +0000 // also two hours late
Try This..................
if you have date in String then convert it into date using #"dd/MM/yyyy hh:mm:ss a"
NSDate *startDate = ...;
NSDate *endDate = ...;
Now Date comparison
// Date Comparision
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:LastDate
toDate:CuurentDate options:0];
Getting the difference between two dates
int months = [components month];
int days = [components day];
int hours = [components hour];
int minutes = [components minute];
You need to set the -dateStyle rather than the time style, as there is also a date contained in that string.
Edit---
You now need to change the -dateFormat to dd/MM/yyyy HH:mm:ss a
I hope this helps
NSString *dtString = #"1900-01-01T11:00:00";
dtString = [dtString stringByReplacingOccurrencesOfString:#"T" withString:#" "];
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:today];
NSDate *toTimeDate = [dateFormatter dateFromString:dtString];
NSString *toTime = [dateFormatter stringFromDate:toTimeDate];

iPhone: Date conversion issues

I need to check an event date, which should be between Current date and 60 days from now. The below code is used, but it is NOT working correctly. Please note, i'm getting event string like this - "2012-04-14T16:50:02Z" from my server.
// current date
double currDateInMilliSecs = [NSDate timeIntervalSinceReferenceDate] * 1000;
NSLog(#"currDateInMilliSecs: %f", currDateInMilliSecs);
// sixty days
double sixtydaysvalue = 60.0 * 24.0 * 3600.0 * 1000.0;
NSLog(#"sixtydaysvalue: %f", sixtydaysvalue);
// add current date + sixt days
double sixtyDaysMilliSecsFromCurrDate = currDateInMilliSecs + sixtydaysvalue;
NSLog(#"sixtyDaysMilliSecsFromCurrDate: %f", sixtyDaysMilliSecsFromCurrDate);
// check does the event date between current date + 60 days
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//[df setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[df setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
//[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
// [eventDict objectForKey:#"begin_at"] gives date string like this "2012-04-14T16:50:02Z" for ex.
NSDate *eventdate = [df dateFromString:[eventDict objectForKey:#"begin_at"]];
NSTimeInterval nowSinceEventDate = [eventdate timeIntervalSince1970];
NSLog(#"nowSinceEventDate: %f", nowSinceEventDate);
double eventDateInMilliSecs = nowSinceEventDate * 1000;
NSLog(#"eventDateInMilliSecs: %f", eventDateInMilliSecs);
// this is not working as expected
if ( eventDateInMilliSecs<sixtyDaysMilliSecsFromCurrDate && eventDateInMilliSecs>currDateInMilliSecs )
{
}
else
{
}
Any help please?
try this
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss SSS"];
Try this:
NSString *dateString = #"2012-04-14T16:50:02Z";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *eventDate = [formatter dateFromString:dateString];
NSTimeInterval nowSinceEventDate = [eventDate timeIntervalSince1970];
NSLog(#"interval = %f", nowSinceEventDate);
UPDATE:
NSString *dateString = #"2012-05-21T16:50:02Z";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *eventDate = [formatter dateFromString:dateString];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:60];
NSDate *minDate = [NSDate date];
NSDate *maxDate = [gregorian dateByAddingComponents:components toDate:minDate options:0];
NSLog(#"eventDate interval = %f", [eventDate timeIntervalSince1970]);
NSLog(#"minDate interval = %f", [minDate timeIntervalSince1970]);
NSLog(#"maxDate interval = %f", [maxDate timeIntervalSince1970]);
BOOL isBetween = (([eventDate compare:minDate] == NSOrderedDescending) && ([eventDate compare:maxDate] == NSOrderedAscending));
NSLog(#"isBetween = %d", isBetween);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss:SSS"];
// [eventDict objectForKey:#"begin_at"] gives "2012-04-14T16:50:02Z"
NSDate *eventdate = [df dateFromString:[eventDict objectForKey:#"begin_at"]];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
SSS for milli seconds

Get time difference between two specific time zones in iPhone?

e.g. I want the time difference between asia/kolkata time and asia/dubai.
NSInteger differenceInSeconds = [timeZone1 secondsFromGMT] - [timeZone2 secondsFromGMT];
Note that this gives the current time difference between those timezones. If the two timezones observe daylight savings at different times of year, the time difference depends on when you evaluate this. If this matters to you, you should use secondsFromGMTForDate: to get the timezone offset at a specific date.
NSDate *now = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init] ;
[df setTimeStyle:NSDateFormatterFullStyle];
[df setTimeZone:[NSTimeZone timeZoneWithName:Str]];//str = timezone1(for you its kolkata)
[df setDateFormat:#"dd-MM-yyyy HH:mm"];
NSString *S1 = [df stringFromDate:now];
[df setDateFormat:#"dd-MM-yyyy HH:mm"];
NSDate *dd = [df dateFromString:S1];
//dd = date1 as per timezone
NSLog(#"dd > %#",dd);
[df release];
NSDate *dt = [NSDate date];
NSLog(#"dt = %#",dt);
NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
[df1 setTimeStyle:NSDateFormatterFullStyle];
[df1 setTimeZone:[NSTimeZone timeZoneWithName:Str2]];//str2=timezone2(for you its dubai)
[df1 setDateFormat:#"dd-MM-yyyy HH:mm"];
NSString *S2 = [df1 stringFromDate:dt];
[df setDateFormat:#"dd-MM-yyyy HH:mm"];
NSDate *dd1 = [df dateFromString:S2];
//dd1 = date2 as per timezone
NSLog(#"dd1 > %#",dd1);
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:dd toDate:dd1 options:0];
NSLog(#"Conversion: %dmin %dhours %ddays %dmoths",[conversionInfo minute], [conversionInfo hour], [conversionInfo day], [conversionInfo month]);
i'm usin this code and its working properly.