Get time difference between two specific time zones in iPhone? - 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.

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

how to take a date without time in iphone

I am try to remove time from date how to do this i try this code it not working proper where i am wrong
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *todaysDate = [NSDate date];
//NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
NSDateComponents*dateComponents = [gregorian components:NSDayCalendarUnit fromDate:todaysDate];
[dateComponents setDay:1];
app.selectionData.fromDateSelected = [gregorian dateByAddingComponents:dateComponents toDate:todaysDate options:0];
//[dateComponents release];
[gregorian release];
Are you trying to do this?
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int comps = NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;
NSDateComponents *dateComponents = [gregorian components:comps fromDate:[NSDate date]];
[dateComponents setDay:[dateComponents day] + 1];
app.selectionData.fromDateSelected = [gregorian dateFromComponents:dateComponents];
[gregorian release];
To only get the date, you can use NSDateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString* currentDate = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];
You can also supply your own format for the date.
For ex:
[dateFormattter setDateFormat:#"yyyy-mm-dd"];
You can refer to UTS #35 and Date Formatting Guide for more options on formatting.
Try this out. This works for me
NSDate *todaysDate = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSString *stringDate = [dateFormat stringFromDate:todaysDate];
NSLog(#"stringDate: %#",stringDate);
[dateFormat release];
EDIT:
NSDate *today = [NSDate date];
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *date = [today addTimeInterval:secondsPerDay];
//Change NSDate *date = [tomorrow addTimeInterval:-secondsPerDay]; for yesterday
NSDate *tomorrow = date;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSString *stringDate = [dateFormat stringFromDate:tomorrow];
NSLog(#"stringDate: %#",stringDate);
[dateFormat release];
Hope this helps you.

iphone NSDate - get todays date and force the time

hopefully a quick one for someone! I am struggling to see why the code below isn't working. I am trying to get today's date (eg: 2010-09-10) and manually adding the time. It always seems to return 00:00:00 for the time though. any ideas where I'm going wrong?
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSString *actualDate = [dateFormatter stringFromDate:[NSDate date]];
NSDate *sDate = [dateFormatter dateFromString:[NSString stringWithFormat:#"%# %#", actualDate, #"01:00:00"]];
NSDate *eDate = [dateFormatter dateFromString:[NSString stringWithFormat:#"%# %#", actualDate, #"23:59:59"]];
The NSDate objects are returning the format 2010-09-10 00:00:00 +01:00 all the time. Somewhere it's just not picking up the time.... any ideas? many thanks.
* UPDATE *
The code below works. I did as suggested and accessed the elements and updated them.
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = #"yyyy-MM-dd hh:mm:ss";
//update for the start date
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSDate *sDate = [calendar dateFromComponents:comps];
//update for the end date
[comps setHour:23];
[comps setMinute:59];
[comps setSecond:59];
NSDate *eDate = [calendar dateFromComponents:comps];
You should use NSCalendar instead then. It allows you to parse the current date and modify its components. Like you can initialize it with today's date and then set the time and then get an NSDate from it.
(Old answer: Because your formatter is configured to only recognize the date part. Add the time part to it (even though its name is NSDateFormatter, it will happily parse dates and times) and you will see the time too.)
I found this question today while looking to do the same thing, create an NSDate with a specific time today. The solution presented wasn't quite what I needed so I came up with this:
NSDate * date;
NSString * string, *timestamp;
NSDateFormatter * formatter;
timestamp = #"17:30";
formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat: #"yyyy-MM-dd "];
[formatter setTimeZone: [NSTimeZone localTimeZone]];
string = [formatter stringFromDate: [NSDate date]];
string = [string stringByAppendingString: timestamp];
[formatter setDateFormat: #"yyyy-MM-dd HH:mm"];
date = [formatter dateFromString: string];