NSDateFormatter not working to set setTimeZone - iphone

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.

Related

How to get current year first date in iphone programmatically

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

Getting next date and previous day date

I basically want to convert a particular date (x) to the previous day date(x - 1 day) and also to the next day date (x + 1 day). I am using the following code for this :
NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)];
However I have my date (x) in NSString format, and I need to convert the NSString(myDateString) to NSDate(myDate) before applying the above code.
I have a NSString containing date in format MM-dd-yyyy.
For converting I am using the following code , but I am getting absurd values.
NSLog(#"myDateString=%#",myDateString);//output:myDateString=10-25-2012//all correct
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-yyyy"];
NSDate *myDate=[formatter dateFromString:myDateString];
NSLog(#"myDate=%#",myDate);//output:myDate=2012-10-24 18:30:00 +0000 // I only want the date to be shown // and why has the format changed
NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)];
NSLog(#"datePlusOneDay=%#",datePlusOneDay);//output:datePlusOneDay=2012-10-25 18:30:00 +0000// I only want the date to come , not time // and why has the format changed
Later again I need to convert the NSDate to NSString
NSString *curentString=[formatter stringFromDate:datePlusOneDay];
NSLog(#"curentString=%#",curentString); //output:curentString=10-26-2012
Similarly I also want to get the previous date.
Please help guys !! and ho ho MERRY CHRISTMAS !!
Do as: componets.day = 1 to obtain the next, -1 for the previous day.
NSDate *date = [NSDate date]; // your date from the server will go here.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *newDate = [calendar dateByAddingComponents:components toDate:date options:0];
NSLog(#"newDate -> %#",newDate);
The below code should get you the previous date:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-1]; // replace "-1" with "1" to get the datePlusOneDay
NSDate *dateMinusOneDay = [gregorian dateByAddingComponents:offsetComponents toDate:myDate options:0];
Merry Xmas :)
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]];
[components setHour:-[components hour]];
[components setMinute:-[components minute]];
[components setSecond:-[components second]];
NSDate *today = [cal dateByAddingComponents:components toDate:[[NSDate alloc] init] options:0]; //This variable should now be pointing at a date object that is the start of today (midnight);
[components setHour:-24];
[components setMinute:0];
[components setSecond:0];
NSDate *yesterday = [cal dateByAddingComponents:components toDate: today options:0];
Try this simple solution for previous date:-
NSDate *datePlusOneDay = [[NSDate date] dateByAddingTimeInterval:-(60 * 60 * 24)];
NSLog(#"datePlusOneDay=%#",datePlusOneDay);
Swift 5 Solution
let calendar = Calendar.current
calendar.date(byAdding: .day, value: -2, to: Date())
function for previousDay
-(void)previousDay
{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
dateString = [dateFormat stringFromDate:today];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
comps.day =-1;
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
EndingDate = [dateFormat stringFromDate:sevenDays];
}
function for next day
-(void)nextDay
{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
dateString = [dateFormat stringFromDate:today];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
comps.day =1;
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
EndingDate = [dateFormat stringFromDate:sevenDays];
}

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

disply the current week start and end date

I want to display the Current week in UINavigationBar and then click on Next or Previous button to display the Previous week or Next week
Example:
July 22 - July 28
July 29 - Auguest 4
To get first date of the week you can do something like this :
- (NSDate *)firstDayOfWeekFromDate:(NSDate *)date {
CFCalendarRef currentCalendar = CFCalendarCopyCurrent();
NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:date];
[components setDay:([components day] - ([components weekday] - CFCalendarGetFirstWeekday(currentCalendar)))];
//[components setDay:(CFCalendarGetFirstWeekday(currentCalendar))];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
CFRelease(currentCalendar);
return [CURRENT_CALENDAR dateFromComponents:components];
}
After getting first week of the day you can calculate days as suggested in above answer by #vikas
:)
NSDate * selectedDate = [NSDate date];
-(IBAction)Week_CalendarActionEvents:(id)sender{
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
NSDate *nextDate;
if(sender==Week_prevBarBtn) // Previous button events
[offsetComponents setDay:-7];
else if(sender==Week_nextBarBtn) // next button events
[offsetComponents setDay:7];
nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:selectedDate options:0];
selectedDate = nextDate;
[selectedDate retain];
NSDateComponents *components = [gregorian components:NSWeekCalendarUnit fromDate:selectedDate];
NSInteger week = [components week];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM YYYY"];
NSString *stringFromDate = [formatter stringFromDate:selectedDate];
[formatter release];
[Week_weekBarBtn setTitle:[NSString stringWithFormat:#"%#,Week %d",stringFromDate,week]];
}

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.