Convert any timezone date in system timezone in iOS - iphone

I am facing problem while converting given date into system time zone in iOS.
Source date: 2013-03-18 03:54:18 // its in AM format
Destination date should be : 2013-03-18 03:30:15 //its in PM format.
How can I get this??
I have tried below code but getting wrong data and difference too.
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSLog(#"Post date::%#",postDate);
NSDate *utc = [fmt dateFromString:postDate];
fmt.timeZone = [NSTimeZone systemTimeZone];
NSString *local = [fmt stringFromDate:utc];
NSLog(#" local %#", local);
NSDate *date1 = [NSDate date];
NSString *currentDateString = [fmt stringFromDate:date1];
NSDate *currentDate = [fmt dateFromString:currentDateString];
NSUInteger flags = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:utc toDate:currentDate options:0];
NSLog(#"difference::%d",[difference day]);
NSLog(#"difference::%d",[difference hour]);
NSLog(#"difference::%d",[difference minute]);
EDIT: Outputs
Post date::2013-03-18 03:20:09
local 2013-03-18 03:20:09
difference::0
difference::13
difference::2

Replace your code from...
fmt.timeZone = [NSTimeZone systemTimeZone];
as like this
fmt.timeZone = [NSTimeZone localTimeZone];
This will works for you...

NSString *openingHour = #"15:05:35 ";
NSDateFormatter *workingHoursFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[workingHoursFormatter setTimeZone:timeZone];
[workingHoursFormatter setDateFormat:#"HH:mm"];
NSDate *openingTime = [workingHoursFormatter dateFromString:openingHour];
Can you try the above code it works for me , alter the date format to your need

Related

Adding minutes to Current time from text input error (iOS)

Currently have a text input from users and which to add that to current time and display on the Screen as a text input in HH:mm format.
Current Code:-
NSString *strCurrentDate;
NSString *strNewDate;
NSDate *date = [NSDate date];
NSDateFormatter *df =[[NSDateFormatter alloc]init];
[df setDateFormat:#"hh:mm"];
strCurrentDate = [df stringFromDate:date];
NSLog(#"Current Time: %#",strCurrentDate);
int minutesToAdd = workingTime.text;
NSCalendar *calendar = [[NSCalendar
alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setMinute:minutesToAdd];
NSDate *newDate= [calendar dateByAddingComponents:components toDate:date options:0];
[df setDateFormat:#"hh:mm"];
strNewDate = [df stringFromDate:newDate];
NSLog(#"workingtime is :%#",workingTime.text);
NSLog(#"New Date and Time: %#",strNewDate);
crewOutTime.text = strNewDate;
However Add's incorrect amount to time When i Change it to int minutesToAdd = 40; to a fixed Value it is correct and works as wanted.
Try
int minutesToAdd = workingTime.text.intValue;
instead of
int minutesToAdd = workingTime.text;
With your code you are setting your minutesToAdd to a pointer.

Convert GMT NSDate to device's current Time Zone

I'm using Parse.com to store some values:
These are GMT values. How do I convert these to the device's current time zone and get NSDate as a result?
NSDate is always represented in GMT. It's just how you represent it that may change.
If you want to print the date to label.text, then convert it to a string using NSDateFormatter and [NSTimeZone localTimeZone], as follows:
NSString *gmtDateString = #"08/12/2013 21:01";
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:#"dd/MM/yyyy HH:mm"];
//Create the date assuming the given string is in GMT
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *date = [df dateFromString:gmtDateString];
//Create a date string in the local timezone
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone localTimeZone].secondsFromGMT];
NSString *localDateString = [df stringFromDate:date];
NSLog(#"date = %#", localDateString);
// My local timezone is: Europe/London (GMT+01:00) offset 3600 (Daylight)
// prints out: date = 08/12/2013 22:01
The easiest method I've found is this:
NSDate *someDateInUTC = …;
NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate *dateInLocalTimezone = [someDateInUTC dateByAddingTimeInterval:timeZoneSeconds];
This is a very clean way to change the NSDate to a local time zone date
extension NSDate {
func toLocalTime() -> NSDate {
let timeZone = NSTimeZone.local
let seconds : TimeInterval = Double(timeZone.secondsFromGMT(for:self as Date))
let localDate = NSDate(timeInterval: seconds, since: self as Date)
return localDate
}
}
taken from https://agilewarrior.wordpress.com/2012/06/27/how-to-convert-nsdate-to-different-time-zones/
Creating an Xcode test case like the following may help us remember the rules "forever":
- (void)test2015_05_23_07_07_07_Toronto {
NSString *utcDateString = #"2015_05_23 12:07:07";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = #"yyyy_MM_dd HH:mm:ss";
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
NSDate *date2015_05_23_12_07_07_UTC = [dateFormatter dateFromString:utcDateString];
XCTAssertTrue([date2015_05_23_12_07_07_UTC.description isEqualToString:#"2015-05-23 12:07:07 +0000"]);
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:#"EST"];
NSString *torontoDateString = [dateFormatter stringFromDate:date2015_05_23_12_07_07_UTC];
XCTAssertTrue([torontoDateString isEqualToString:#"2015_05_23 07:07:07"]);
// change format to add ZZZ
dateFormatter.dateFormat = #"yyyy_MM_dd HH:mm:ss ZZZ";
torontoDateString = [dateFormatter stringFromDate:date2015_05_23_12_07_07_UTC];
XCTAssertTrue([torontoDateString isEqualToString:#"2015_05_23 07:07:07 -0500"]);
XCTAssertEqual(1432382827, [date2015_05_23_12_07_07_UTC timeIntervalSince1970]);
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:#"EST"];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date2015_05_23_12_07_07_UTC];
XCTAssertEqual(2015, components.year);
XCTAssertEqual(5, components.month);
XCTAssertEqual(23, components.day);
XCTAssertEqual(7, components.hour);
XCTAssertEqual(7, components.minute);
XCTAssertEqual(7, components.second);
}
You could use a NSDateFormatter to achieve this result.
NSString *dateAsString = #"08/07/2013 04:06";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/MM/yyyy HH:mm"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[df setTimeZone:gmt];
NSDate *myDate = [df dateFromString: dateAsString];
NSLog(#"date: %#", myDate);
There are many answers to this question but I would recommend this one:
Convert GMT NSDate to device's current Time Zone
NSString *dateStr = #"2012-07-16 07:33:01";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter1 dateFromString:dateStr];
NSLog(#"date : %#",date);
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone]; // <- Local time zone
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date1];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date1];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date1] autorelease];
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:#"dd-MMM-yyyy hh:mm"];
[dateFormatters setDateStyle:NSDateFormatterShortStyle];
[dateFormatters setTimeStyle:NSDateFormatterShortStyle];
[dateFormatters setDoesRelativeDateFormatting:YES];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateStr = [dateFormatters stringFromDate: destinationDate];
NSLog(#"DateString : %#", dateStr);

Issue in adding time to array of date

I am trying to add hour and minutes to array of dates following is my code and i have put NSLog of old array and after array
NSDate* date= _timePicker.date;
NSDateFormatter *formatter=[[[NSDateFormatter alloc]init]autorelease];
[formatter setDateFormat:#"hh:mm"];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
[formatter setTimeStyle:NSDateFormatterLongStyle];
NSDateFormatter *formatter1=[[[NSDateFormatter alloc]init]autorelease];
[formatter1 setDateFormat:#"dd:MM:yyyy"];
[formatter1 setTimeZone:[NSTimeZone systemTimeZone]];
[formatter1 setTimeStyle:NSDateFormatterLongStyle];
NSDateFormatter *formatter3=[[[NSDateFormatter alloc]init]autorelease];
[formatter3 setDateFormat:#"dd-MM-yyyy hh:mm"];
[formatter3 setTimeZone:[NSTimeZone systemTimeZone]];
[formatter3 setTimeStyle:NSDateFormatterLongStyle];
NSString *timeselected =[formatter stringFromDate:date];
NSLog(#"we have picked time %#",timeselected);
NSDate *date2 = [formatter dateFromString:timeselected];
// NSLog(#"date2%#",dateSelected );
NSLog(#"old%#",delegate.notificationBirthDateArray);
old(
"15/08/2013",
"15/07/2014",
"15/07/2014",
"07/06/2014",
"15/01/2014",
"27/01/2014",
"20/01/2014",
"22/06/2014",
"29/08/2013",
"15/06/2014",
"16/07/2013"
)
for (int i=0; i<[delegate.notificationBirthDateArray count]; i++) {
NSDate *date1 = [formatter1 dateFromString:[delegate.notificationBirthDateArray objectAtIndex:i]];
// NSLog(#"date2%#",date2);
// NSLog(#"array%#",date1);
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Extract date components into components1
NSDateComponents *components1 = [gregorianCalendar components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
fromDate:date1];
// Extract time components into components2
NSDateComponents *components2 = [gregorianCalendar components:NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:date2];
// Combine date and time into components3
NSDateComponents *components3 = [[NSDateComponents alloc] init];
[components3 setYear:components1.year];
[components3 setMonth:components1.month];
[components3 setDay:components1.day];
[components3 setHour:components2.hour];
[components3 setMinute:components2.minute];
// when i nslog this components they are printed perfectly
// Generate a new NSDate from components3.
NSDate *combinedDate = [gregorianCalendar dateFromComponents:components3];
// combinedDate contains both your date and time!
NSString *lastdate =[formatter3 stringFromDate:combinedDate];
NSLog(#"combinedDate%#",lastdate);
[delegate.notificationBirthDateArray removeObjectAtIndex:i];
[delegate.notificationBirthDateArray insertObject:lastdate atIndex:i];
}
NSLog(#"new%#",delegate.notificationBirthDateArray);
new(
"6:00:00 PM GMT+05:30",
"6:00:00 PM GMT+05:30",
"6:00:00 PM GMT+05:30",
"6:00:00 PM GMT+05:30",
"6:00:00 PM GMT+05:30",
"6:00:00 PM GMT+05:30",
"6:00:00 PM GMT+05:30",
"6:00:00 PM GMT+05:30",
"6:00:00 PM GMT+05:30",
"6:00:00 PM GMT+05:30",
"6:00:00 PM GMT+05:30"
)
Issue is time which is obtained gets added in correct way which you see above, but where is my dates gone? they should be there too.
Please help me with this.
edited and imporved code but still same problem
NSArray*arr = [NSArray arrayWithArray:delegate.notificationBirthDateArray];
NSDate* date= _timePicker.date;
NSDateFormatter *formatter=[[[NSDateFormatter alloc]init]autorelease];
[formatter setDateFormat:#"hh:mm"];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
[formatter setTimeStyle:NSDateFormatterLongStyle];
NSDateFormatter *formatter1=[[[NSDateFormatter alloc]init]autorelease];
[formatter1 setDateFormat:#"dd/MM/yyyy"];
NSDateFormatter *formatter3=[[[NSDateFormatter alloc]init]autorelease];
[formatter3 setDateFormat:#"dd/MM/yyyy hh:mm a"];
[formatter3 setTimeZone:[NSTimeZone systemTimeZone]];
[formatter3 setTimeStyle:NSDateFormatterLongStyle];
NSString *timeselected =[formatter stringFromDate:date];
NSLog(#"we have picked time %#",timeselected);
NSDate *date2 = [formatter dateFromString:timeselected];
// NSLog(#"date2%#",dateSelected );
NSLog(#"old%#",delegate.notificationBirthDateArray);
for (int i=0; i<arr.count; i++) {
NSString *datefromarray = [[NSString alloc]initWithString:[delegate.notificationBirthDateArray objectAtIndex:i]];
NSDate *date1 = [formatter1 dateFromString:datefromarray];
// NSLog(#"hour time %#",[delegate.notificationBirthDateArray objectAtIndex:i]);
NSLog(#"hour time %#",date2);
NSLog(#"date%#",date1);
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Extract date components into components1
NSDateComponents *components1 = [gregorianCalendar components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
fromDate:date1];
// Extract time components into components2
NSDateComponents *components2 = [gregorianCalendar components:NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:date2];
// Combine date and time into components3
NSDateComponents *components3 = [[NSDateComponents alloc] init];
[components3 setYear:components1.year];
[components3 setMonth:components1.month];
[components3 setDay:components1.day];
[components3 setHour:components2.hour];
[components3 setMinute:components2.minute];
// Generate a new NSDate from components3.
NSDate *combinedDate = [gregorianCalendar dateFromComponents:components3];
// combinedDate contains both your date and time!
NSString *lastdate =[formatter3 stringFromDate:combinedDate];
NSLog(#"combinedDate%#",lastdate);
[delegate.notificationBirthDateArray removeObjectAtIndex:i];
[delegate.notificationBirthDateArray insertObject:lastdate atIndex:i];
}
NSLog(#"new%#",delegate.notificationBirthDateArray);
}
I see one issue here :
for (int i=0; i<[delegate.notificationBirthDateArray count]; i++) {
//Your code
[delegate.notificationBirthDateArray removeObjectAtIndex:i];
[delegate.notificationBirthDateArray insertObject:lastdate atIndex:i];
}
You shouldn't use the notificationBirthDateArray in the for loop and do actions on it , it will bring unexpected problems,so i recommend on using another array as a placeholder in the for loop.
NSArray*arr = [NSArray arrayWithArray:delegate.notificationBirthDateArray];
then if you want do this:
for (int i=0; i<arr.count; i++)
{
//Your code
[delegate.notificationBirthDateArray removeObjectAtIndex:i];
[delegate.notificationBirthDateArray insertObject:lastdate atIndex:i];
}
Could be more things here, but i think you should modify like i mentioned and post the new outcome.
Remove from the formatter1 the line :
[formatter1 setTimeStyle:NSDateFormatterLongStyle];
and modify the line :
[formatter1 setDateFormat:#"dd:MM:yyyy"];
to :
[formatter1 setDateFormat:#"dd/MM/yyyy"];
If your string dates are exactly like in the old array;
To add an hours/minutes time interval to an NSDate, use dateWithTimeInterval:sinceDate:.
NSDate* oldDate = <some date>;
NSTimeInterval timeToAdd = ((hoursToAdd * 60) + minutesToAdd) * 60.0;
NSDate* newDate = [theDate dateWithTimeInterval:timeToAdd sinceDate:oldDate];
You could also do it with NSDateComponents, or by formatting the date, manipulating the characters, and scanning it back to NSDate, but both take dozens of lines and are fraught with chances for error.
(However, if you are starting with a character date, and you just want to add a "boiler plate" time value, just concatenate the pieces together and scan the result:
NSString* oldDate = #"22/06/14";
NSString* dateWithTime = [oldDate appendString:#" 6:00:00 PM GMT+05:30"];
NSDateFormatter* df = [NSDateFormatter new];
df.dateFormat = #"dd/MM/yy h:mm:ss A 'GMT'ZZZZZ"; (or something like that)
NSDate* scannedDate = [df dateFromString:dateWithTime];
(Or, if you don't need the NSDate, skip the date formatter entirely.)

Compare current time with fixed time 05:00:00 PM

How will I compare current time [NSDate date] with fixed time 05:00:00 PM.
That 05:00 PM is already passed or not. I just need BOOL check for this.
- (BOOL)past5pm
{
NSCalendar *gregorianCalender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [gregorianCalender components:NSHourCalendarUnit fromDate:[NSDate date]];
if([components hour] >= 17) // NSDateComponents uses the 24 hours format in which 17 is 5pm
return YES;
return NO;
}
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH.mm"];
NSDate *currentDate = [NSDate date];
NSString *curDate = [dateFormatter stringFromDate:currentDate];
if ([curDate doubleValue] >= 17.00)
{
//set your bool
}
Try this
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"hh:mm:ss a"];
NSDate* date = [NSDate date];
//Get the string date
NSString* str = [dateFormatter stringFromDate:date];
NSDate *firstDate = [dateFormatter dateFromString:#"05:00:00 PM"];
NSDate *secondDate = [dateFormatter dateFromString:str];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
NSLog(#"Time Diff - %f",timeDifference);
You can probably use plain C style code and get the difference as an integer and then decide what you need to return from the comparison function depending on wether the difference is positive or negative. You can compare minutes this way as well. Dont forget to import time.h.
time_t now = time(NULL);
struct tm oldCTime;
localtime_r(&now, &oldCTime);
int hours = oldCTime.tm_hour;
int diff = 17-hours;
NSLog(#"Time difference is: %d.", diff);

How to find days between dates stored in 2 strings

I have two strings both are in following date format (2011-03-22).
i have to compare them and find number of days between them.
Can anyone tell me how to do this..
Please also tell me the correct method to convert them back to NSDate.
Might be a couple of errors as i just typed this, but it speaks for itself and you should get the idea.
NSString *dateStringA = #"2011-03-22";
NSString *dateStringB = #"2011-03-27";
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
df.dateFormat = #"yyyy-MM-dd";
NSDate *dateA = [df dateFromString:dateStringA];
NSDate *dateB = [df dateFromString:dateStringB];
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:dateA toDate:dateB options:0];
int daysBetweenDates = comps.day; //This is your days between the 2 dates
NSDate *intervalDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; //This date object represents the duration between them
 For string to date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];
for date to string
NSString *date = [[NSDate date] description];