Issue in adding time to array of date - iphone

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.)

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

Convert any timezone date in system timezone in iOS

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

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

objective-c: converting date string into day of the week + month name

A beginner's problem, but I was wondering if anyone could help me with this:
I need to set four strings according to a string which contains a certain date (e.g. #"Apr 7, 2011"):
a string which will take the day of the week (abbreviated: Mon, Tue, Wed, Thu, Fri, Sat, Sun): e.g. #"Thu"
a string which will take the day, e.g. #"7"
a string which will take the month, e.g. #"April"
and a string which will take the year, e.g. #"2011"
So far, I found this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:usLocale];
NSLog(#"Date for locale %#: %#",
[[dateFormatter locale] localeIdentifier], [dateFormatter stringFromDate:date]);
// Output:
// Date for locale en_US: Jan 2, 2001
So this would give me a certain formatted date. I was wondering, however, how I can access certain parts of this date. There is the - (NSArray *)weekdaySymbols but I have no idea how to work this one and the documentation is quite frugal.
Any hints from calendar experts would be very welcome.
EDIT:
I guess this is part of the solution:
NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_GB"];
NSString *gbFormatString = [NSDateFormatter dateFormatFromTemplate:#"EdMMM" options:0 locale:gbLocale];
NSLog(#"gbFormatterString: %#", gbFormatString);
// Output: gbFormatterString: EEE d MMM, e.g. Thu 7 Apr
n.evermind,
You're going to need something like this:
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"MMM dd, yyy"];
date = [formatter dateFromString:#"Apr 7, 2011"];
NSLog(#"%#", [formatter stringFromDate:date]);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger year = [components year];
NSInteger month=[components month]; // if necessary
NSInteger day = [components day];
NSInteger weekday = [components weekday]; // if necessary
NSDateFormatter *weekDay = [[[NSDateFormatter alloc] init] autorelease];
[weekDay setDateFormat:#"EEE"];
NSDateFormatter *calMonth = [[[NSDateFormatter alloc] init] autorelease];
[calMonth setDateFormat:#"MMMM"];
NSLog(#"%# %i %# %i", [weekDay stringFromDate:date], day, [calMonth stringFromDate:date], year );
output
2011-04-07 12:49:23.519 test[7296:207] Apr 07, 2011
2011-04-07 12:49:23.521 test[7296:207] Thu 7 April 2011
Cheers, Jordan
You should take a Look on NSDateFormatter
#n.evermind
You should actually look at NSCalendar and specifically the - components:fromDate method which gives you the NSDateComponents object which has all the peices you want.