Split a NSDate into day and time - ios

I am trying to split a NSDate I receive from web service into two different dates in order to populate a tableView for events with sections for each day. I figured the least complicated way to do the latter is to create a fetch request looking for unique days.
So I try to create a NSDate "day" but having the time component set to 00:00. I wonder if there is a more efficient way to achieve this:
if (eventoItemList.count > 0) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
[dayFormatter setDateFormat:#"yyyy-MM-dd"];
for (GDataXMLElement *eventoItem in eventoItemList) {
BOEvent *event = [[BOEvent alloc] init];
NSString *idEventStr = [[[eventoItem elementsForName:#"id"] objectAtIndex:0] stringValue];
NSString *name = [[[eventoItem elementsForName:#"titulo"] objectAtIndex:0] stringValue];
NSString *type = [[[eventoItem elementsForName:#"tipo"] objectAtIndex:0] stringValue];
NSString *descr = [[[eventoItem elementsForName:#"descripcion"] objectAtIndex:0] stringValue];
NSString *address = [[[eventoItem elementsForName:#"direccion"] objectAtIndex:0] stringValue];
NSDate *date = [dateFormatter dateFromString:[[[eventoItem elementsForName:#"fecha"] objectAtIndex:0] stringValue]];
NSString *action = [[[eventoItem elementsForName:#"accion"] objectAtIndex:0] stringValue];
[event setIdEvent:[idEventStr integerValue]];
[event setName:name];
[event setType:type];
[event setDesc:descr];
[event setAddress:address];
[event setAction:action];
[event setDate:date];
[event setDayDate:[dayFormatter dateFromString:[dayFormatter stringFromDate:date]]];
[events addObject:event];
}
}
Thank you for your help.

sample code for splitting a NSDate into two NSDates (date only, time only)
NSDate *date = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *comps = [gregorian components:unitFlags fromDate:date];
NSDate *dateOnly = [gregorian dateFromComponents:comps];
unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit;
comps = [gregorian components:unitFlags fromDate:date];
NSDate *timeOnly = [gregorian dateFromComponents:comps];
NSLog(#"%# = \n\tDate: %# \n\tTime: %#", date, dateOnly, timeOnly);
sample code for outputting NSDate in two NSStrings
NSDate *date = [NSDate date];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateStyle:NSDateFormatterFullStyle];
[f setTimeStyle:NSDateFormatterNoStyle];
NSString *dateOnly = [f stringFromDate:date];
[f setTimeStyle:NSDateFormatterFullStyle];
[f setDateStyle:NSDateFormatterNoStyle];
NSString *timeOnly = [f stringFromDate:date];
NSLog(#"%# = \n\tDate: %# \n\tTime: %#", date, dateOnly, timeOnly);

Related

incompatible pointer type sending NSString to parameter of type NSDate* _Nonnull ios Objective c

I have the following code. Here I tried two methods to get the date and time. If i use formatter it gives me the above error. If I do not use it the date format is not correct and plus the time which i get is also incorrect. Kindly help.
NSDate *pickupHoursLate;
NSDate *dropHoursLate;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy HH:mm"];
NSLog(#"Old Date and Time : %#",[formatter stringFromDate:[NSDate date]]);
this give me output like this 12-07-2016 18:32 which I want
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [[NSDateComponents alloc] init];
int pickHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:#"pickupPriorTimePeriod"] intValue];
[components setHour:pickHoursToAdd];
pickupHoursLate = [calender dateByAddingComponents:components toDate:[formatter stringFromDate:[NSDate date]] options:0];
This Line gives me the error
int dropHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:#"dropPriorTimePeriod"] intValue];
[components setHour:dropHoursToAdd];
dropHoursLate = [calender dateByAddingComponents:components toDate:[NSDate date] options:0];
This Line gives me the value 2016-07-12 15:02:51 +0000 after adding 2 hrs to current time but here the time is incorrect
Try this....
NSDate *pickupHoursLate;
NSDate *dropHoursLate;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy HH:mm"];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(#"Old Date and Time : %#",[formatter stringFromDate:[NSDate date]]); **<this give me output like this 12-07-2016 18:32 which I want>**
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [[NSDateComponents alloc] init];
int pickHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:#"pickupPriorTimePeriod"] intValue];
[components setHour:pickHoursToAdd];
//Editing start
NSString *dateStr = [formatter stringFromDate:[NSDate date]] ;
NSDate *date = [formatter dateFromString:dateStr];
pickupHoursLate = [calender dateByAddingComponents:components toDate: date options:0]; **<This Line gives me the error>**
//Editing End
int dropHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:#"dropPriorTimePeriod"] intValue];
[components setHour:dropHoursToAdd];
dropHoursLate = [calender dateByAddingComponents:components toDate:[NSDate date] options:0]; **<This Line gives me the value "2016-07-12 15:02:51 +0000" after adding 2 hrs to current time but here the time is incorrect>**

How to calculate the total of traveled time

I need to get a NSString that displays a total of traveled time using 2 NSStrings
I have
NSString *origin = [NSString stringWithFormat:#"5:30"];
NSString *destiny = [NSString stringWithFormat:#"6:00"];
The problem is I don't know how to format this NSStrings to NSDate and do destiny - origin so the output would be a new NSString that says 30 minutes
EDIT: I've just investigate a little about the NSDateFormatter but if I use it:
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSDate * mydate = [dateFormatter dateFromString:origin];
NSDate returns me a nil Is there something wrong?
Any help will be very appreciated.
NSString *origin = #"5:30";
NSString *destiny = #"6:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"H:mm"];
NSDate *originDate = [dateFormatter dateFromString:origin];
NSDate *destinyDate = [dateFormatter dateFromString:destiny];
NSTimeInterval interval = [destinyDate timeIntervalSinceDate:originDate];
NSDate *intervalDate = [NSDate dateWithTimeInterval:interval sinceDate:originDate ];
NSDateComponents *comps =[[NSCalendar currentCalendar] components:NSMinuteCalendarUnit
fromDate:originDate
toDate:intervalDate
options:0];
Now the NSDateComponents will hold the difference in minutes
NSLog(#"%ld", [comps minute]);
will log 30
If you would like the hours and minutes, you can do
NSString *origin = #"5:30";
NSString *destiny = #"7:00";
// ....
NSDateComponents *comps =[[NSCalendar currentCalendar] components: (NSMinuteCalendarUnit|NSHourCalendarUnit)
fromDate:originDate
toDate:intervalDate
options:0];
Now comps will hold the 90 minutes as 1 hour and 30 minutes.
NSLog(#"%ld %ld", [comps hour],[comps minute]);
logs 1 30
NSString *origin = #"5:30";
NSString *destiny = #"6:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"H:mm"];
NSDate *originDate = [dateFormatter dateFromString:origin];
NSDate *destinyDate = [dateFormatter dateFromString:destiny];
NSTimeInterval diffInSeconds = [destinyDate timeIntervalSinceDate:originDate];
NSTimeInterval diffInMinutes = diffInSeconds / 60;
NSString *minutesString = [NSString stringWithFormat:#"%0.0f", diffInMinutes];

Hi I need time like this #"January 12th 2014 at 11:45 pm"

NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.dateFormat = #"MMMM FF yyyy";
NSString *dateStr = [dateFormat stringFromDate:date];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
timeFormat.dateFormat = #"HH:mm aa";
NSString *timeStr = [[timeFormat stringFromDate:date] lowercaseString];
NSLog(#"%# at %#", dateStr, timeStr);
Now I got my solution like this "February 15 2014 at 04:30 pm" but I need like this "February 15th 2014 at 04:30 pm". That is, I want it to say "15th" instead of just "15".
How do I do that?
You'll need to modify the NSDateFormatter literal, and this will only work for english localizations. You can also do the complete date/time formatting in one pass:
untested
NSTimeZone *tz = [NSTimeZone timeZoneWithAbbreviation:#"UTC"]; // or whatever
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:tz];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:tz];
[formatter setCalendar:calendar];
NSDate *date = [NSDate date];
NSDateComponents *comps = [calendar components:NSDayCalendarUnit
fromDate:date];
// 1 = st
// 2 = nd
// 3 = rd
// 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 = th
// 21 = st
// 22 = nd
// 23 = rd
// 24,25,26,27,28,29,30 = th
// 31 = st
NSString *suffix;
if (comps.day == 11) {
suffix = #"th";
} else {
switch (comps.day % 10) {
case 1: suffix = #"st"; break;
case 2: suffix = #"nd"; break;
case 3: suffix = #"rd"; break;
default: suffix = #"th"; break;
}
}
formatter.dateFormat = [NSString stringWithFormat:#"MMMM d'%#' yyyy 'at' hh:mm aa", suffix];
NSString *timeStr = [formatter stringFromDate:date];
try this.
NSString *suffix_string = #"|st|nd|rd|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|st|nd|rd|th|th|th|th|th|th|th|st";
NSArray *suffixes = [suffix_string componentsSeparatedByString: #"|"];
NSDateFormatter *monthDayFormatter = [[NSDateFormatter alloc] init];
[monthDayFormatter setDateFormat:#"d"];
NSDateFormatter *dateFormateHeader = [[NSDateFormatter alloc]init];
int date_day = [[monthDayFormatter stringFromDate:[NSDate date]] intValue];
NSString *suffix = [suffixes objectAtIndex:date_day];
[dateFormateHeader setDateFormat:[NSString stringWithFormat:#"MMMM d'%#' yyyy' at 'hh:mm a",suffix]];
NSString *prefixDateString = [dateFormateHeader stringFromDate:[NSDate date]];
NSLog(#"%#",prefixDateString);
if you'd prefer compact solutions, that makes the proper job for you:
- (NSString *)formattedDateFrom:(NSDate *)date {
NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setPMSymbol:#"pm"];
[_dateFormatter setAMSymbol:#"am"];
[_dateFormatter setDateFormat:#"MMMM dd'%#' YYYY 'at' hh:mm aa"];
return [NSString stringWithFormat:[_dateFormatter stringFromDate:date], [[#"st,nd,rd,th,th,th,th,th,th,th,th,th,th,th,th,th,th,th,th,th,st,nd,rd,th,th,th,th,th,th,th,st" componentsSeparatedByString:#","] objectAtIndex:[[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date].day]];
}
USe following method
NSString *myDateString = [self getDateFroMyFormation:[NSDate date]];
NSLog(#"%#", myDateString);
And method code is
-(NSString *)getDateFroMyFormation:(NSDate *)todayDate
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ;
NSDateComponents *dateComponents = [gregorian components:units fromDate:todayDate];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger day = [dateComponents day];
NSInteger year = [dateComponents year];
NSDateFormatter *calMonth = [[NSDateFormatter alloc] init];
[calMonth setDateFormat:#"MMMM"];
NSDateFormatter *hourTimer = [[NSDateFormatter alloc] init];
[hourTimer setDateFormat:#"a"];
NSString *strDay = #"";
if (day>0)
{
if (day == 1 || day == 21 || day == 31)
strDay = [NSString stringWithFormat:#"%dst",day];
else if (day == 2 || day == 22)
strDay = [NSString stringWithFormat:#"%dnd",day];
else if (day == 3 || day == 23)
strDay = [NSString stringWithFormat:#"%drd",day];
else
{
strDay = [NSString stringWithFormat:#"%dth",day];
}
}
//"February 15th 2014 at 04:30 pm"
NSString *strDateFormation = [NSString stringWithFormat:#"%# %# %d at %d:%d %#", [calMonth stringFromDate:todayDate], strDay, year, hour, minute, [hourTimer stringFromDate:todayDate]];
return strDateFormation;
}
NSDate *dateTemp = [NSDate date];
NSLog(#"Current date%#",dateTemp);
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateStyle:NSDateFormatterMediumStyle];
NSLog(#"NSDateFormatterMediumStyle %#",[dateFormat2 stringFromDate:dateTemp]);
NSArray *arr =[[dateFormat2 stringFromDate:dateTemp] componentsSeparatedByString:#","];
NSLog(#"%#th %#",[arr objectAtIndex:0],[arr objectAtIndex:1]);

Attempting to format date month to full name returns (null)

I using the following code to try to convert the numerical month (5) to the full name (May). When I change the setting from MM to MMMM, however, it just returns null. Why is this?
NSDate *date = [birthday getDate];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
NSInteger year = [components year];
if (year == 1604) {
NSString *monthNumberString = [NSString stringWithFormat:#"%d", [components month]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM"];
NSDate *date = [formatter dateFromString:monthNumberString];
NSString *stringFromDate = [formatter stringFromDate:date];
NSString *monthDay = [NSString stringWithFormat:#"%#, %d", stringFromDate, [components day]];
cell.birthdayLabel.text = monthDay;
} else {
...
}
Try
NSDate *date = [birthday getDate];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
fromDate:date];
NSInteger year = [components year];
if (year == 1604)
{
NSString *monthNumberString = [NSString stringWithFormat:#"%d", [components month]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM"];
NSDate *date = [formatter dateFromString:monthNumberString];
[formatter setDateFormat:#"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:date];
NSString *monthDay = [NSString stringWithFormat:#"%#, %d", stringFromDate, [components day]];
NSLog(#"%#",monthDay);
cell.birthdayLabel.text = monthDay;
}
else {
}
You already have the date. Just format it:
NSDate *date = [birthday getDate];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
NSInteger year = [components year];
if (year == 1604) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM, d"];
NSString *stringFromDate = [formatter stringFromDate:date];
cell.birthdayLabel.text = stringFromDate;
} else {
...
}

Issue with NSDate from NSDateComponents

i have a string like 2013-03-05T07:37:26.853 and i want to get the Output : 2013-03-05 07:37:26. I want the final output in NSDate object. i am using below function to convert desire output. and it returning wrong time.
- (NSDate *) getDateFromCustomString:(NSString *) dateStr
{ NSArray *dateStrParts = [dateStr componentsSeparatedByString:#"T"];
NSString *datePart = [dateStrParts objectAtIndex:0];
NSString *timePart = [dateStrParts objectAtIndex:1];
NSArray *dateParts = [datePart componentsSeparatedByString:#"-"];
NSArray *timeParts = [timePart componentsSeparatedByString:#":"];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:[[timeParts objectAtIndex:0] intValue]];
[components setMinute:[[timeParts objectAtIndex:1] intValue]];
[components setSecond:[[timeParts objectAtIndex:2] intValue]];
[components setYear:[[dateParts objectAtIndex:0] intValue]];
[components setMonth:[[dateParts objectAtIndex:1] intValue]];
[components setDay:[[dateParts objectAtIndex:2] intValue]];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDate *date = [currentCalendar dateFromComponents:components];
NSLog(#"Date 1:%#",date); // Returns wrong time (2013-03-05 02:07:26)
/* i had tried the below.
NSDateFormatter * format = [[NSDateFormatter alloc] init];
[format setTimeZone:NSTimeZoneNameStyleStandard];
[format setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSLog(#"Date 2:%#",[format stringFromDate:date]); // Returns correct date (2013-03-05 07:37:26)
NSDate *fDate = [format dateFromString:[format stringFromDate:date]];
DLog(#"Date 3:%#",fDate); // Returns wrong time (2013-03-05 02:07:26)
*/
[components release];
return date;
}
Plz suggest me if any idea.
What you're seeing here is a time zone issue. If you want to NSLog a correct looking date, we'll need to give the input string a GMT time zone:
Add this in your code and see what happens:
[components setTimeZone: [NSTimeZone timeZoneForSecondsFromGMT: 0]];
Try this,
NSString *departTimeDate = #"2013-03-05T07:37:26.853";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS"];
NSDate *date = [dateFormatter dateFromString:departTimeDate];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSLog(#"Expected Result___ %#",[dateFormatter stringFromDate:date]); //2013-03-05 07:37:26
Try this : issue is Time zone.
+ (NSDate *) getDate:(NSString *) dateStr
{
NSArray *dateStrParts = [dateStr componentsSeparatedByString:#"T"];
NSString *datePart = [dateStrParts objectAtIndex:0];
NSString *timePart = [dateStrParts objectAtIndex:1];
NSString *t = [[timePart componentsSeparatedByString:#"."] objectAtIndex:0];
NSString *newDateStr = [NSString stringWithFormat:#"%# %#",datePart,t];
//2013-03-05 07:37:26
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [df dateFromString:newDateStr];
DLog(#"%#",date);
return date;
}

Resources