Issue with NSDate from NSDateComponents - ios

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

Related

get Timezone in format of UTC+5:30

I want to get timezone of user in String formatted like UTC+5:30
I have tried to get like this.
NSTimeZone *timeZone=[NSTimeZone localTimeZone];
NSLog(#"%# || %#",timeZone.abbreviation,timeZone.name);
This gives me this output.
(but not getting time as i want)
IST || Asia/Kolkata
Thanks
You can use NSDate Formatter to get the offset from UTC:
NSDateFormatter *dates = [[NSDateFormatter alloc]init];
[dates setDateFormat:#"Z"];
NSLog(#"%#", [dates stringFromDate:[NSDate date]]);
This will log: +0530 (+5:30)
If you want it in your specific format you can simply do:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"Z"];
NSString *offetString = [dateFormatter stringFromDate:[NSDate date]];
NSString *formattedString = [NSString stringWithFormat:#"UTC%#:%#",[offetString substringWithRange:NSMakeRange(0, 3)],[offetString substringWithRange:NSMakeRange([offetString length] - 2, 2)]];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
df.timeZone = [NSTimeZone localTimeZone];
df.dateFormat = #"Z";
NSString *localTimeZoneOffset = [df stringFromDate:[NSDate date]];
NSLog(#"%#",localTimeZoneOffset);
You will get output like,
+0530 for UTC+5:30.
Update : (As asked in comment)
Try below code for your desired format,
NSDateFormatter *df = [[NSDateFormatter alloc]init];
df.timeZone = [NSTimeZone localTimeZone];
df.dateFormat = #"Z";
NSString *localTimeZoneOffset = [df stringFromDate:[NSDate date]];
NSLog(#"%#",localTimeZoneOffset);
NSString *one = [localTimeZoneOffset substringToIndex:1];
NSString *two = [localTimeZoneOffset substringWithRange:NSMakeRange(1, 2)];
NSString *three = [localTimeZoneOffset substringWithRange:NSMakeRange(3, 2)];
NSString *result = [NSString stringWithFormat:#"utc%#%#:%#",one,two,three];
NSLog(#"result : %#",result);

how to convert string date to nsdate using formatter?

i follow stackOverflow answer and Write a code but i Don't know What happen.it won't work. plz,any one can solve it for me. i use fooling code....
NSMutableArray *movieDate;
NSArray *temp1 = [_dicUpcomingMovie objectForKey:#"results"];
for (NSDictionary *temp2 in temp1)
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSString *datestring = [temp2 valueForKey:#"release_date"];
//NSDate *myDate = [[NSDate alloc]init];
[formatter setDateFormat:#"dd MMM,YYYY"];
NSDate *date = [formatter dateFromString:datestring];
NSLog(#"%#",date);
[movieDate addObject:date];
NSLog(#"%#",movieDate);
}
so this is it. the above code was not work myDate object still nil
I believe that datestring doesn't match the format you specified. See NSDateFormatter for a complete example.
NSMutableArray *movieDate=[[NSMutableArray alloc]init];;
NSArray *temp1 = [_dicUpcomingMovie objectForKey:#"results"];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
for (int i=0 ;i<temp1.count;i++)
{
NSString *datestring = [[temp1 objectatindex:i]valueForKey:#"release_date"];
[serverFormatter setTimeZone:[NSTimeZone localTimeZone]];
[serverFormatter setDateFormat:#"dd,MMM,YYYY"];
NSDate *date = [serverFormatter dateFromString:dateString1];
[movieDate addObject:date];
}
NSLog(#"%#",movieDate);
Try this,
NSMutableArray *movieDate;
NSArray *temp1 = [_dicUpcomingMovie objectForKey:#"results"];
for (NSDictionary *temp2 in temp1)
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSString *datestring = [temp2 valueForKey:#"release_date"];
//NSDate *myDate = [[NSDate alloc]init];
[formatter setDateFormat:#"dd MM,YYYY"];
NSDate *date = [formatter dateFromString:datestring];
NSLog(#"%#",date);
[movieDate addObject:date];
NSLog(#"%#",movieDate);
}

How to get NSTimeZone from string?

Assume that I have string like this from server #"2014-03-08T16:59+0000".
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [self dateFromJSONString:#"2014-03-08T16:59+0000"];
NSDateComponents *dateComponents = [calendar components:(NSTimeZoneCalendarUnit) fromDate:date];
NSLog(#"TimeZone is %#", [[dateComponents timeZone] abbreviation]);
But the TimeZone is not base on the string, it based on the currentTimeZone of the device.
Is it possible to extract timeZone from string ?
You have to parse the offset from GMT from your string yourself.
Something like this, but you'll have to tweak for your slightly different format:
/**
This is assuming format yyyy-MM-dd'T'HH:mm:ssZZZZZ . ie the last 5 chars are timezone offset from gtm in the form (+|-)##:##
*/
-(NSTimeZone*)timezoneFromDateString:(NSString*)dateString {
NSTimeZone *timezone = nil;
NSString *timezoneComponent = [dateString substringFromIndex:19];
if(timezoneComponent.length == 6) {
NSArray *components = [[timezoneComponent substringFromIndex:1] componentsSeparatedByString:#":"];
NSInteger offset = [[timezoneComponent substringToIndex:1] isEqualToString:#"-"] ? -1 : 1;
if(components.count == 2) {
offset *= [components[0] integerValue] * 60*60 + [components[1] integerValue] *60;
timezone = [NSTimeZone timeZoneForSecondsFromGMT:offset];
}
}
return timezone;
}
-(NSArray*)convertToLocalDate:(NSString*)dateStr{
NSArray *convert;
NSString *time=#"";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy hh:mm:ss a"];
NSDate *date = [dateFormatter1 dateFromString:dateStr];
//NSLog(#"date : %#",date);
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date] ;
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:#"dd.MM.yyyy"];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateStr = [dateFormatters stringFromDate: destinationDate];
NSDateFormatter *dateFormatters1 = [[NSDateFormatter alloc] init];
[dateFormatters1 setDateFormat:#"hh:mm a"];
[dateFormatters1 setTimeZone:[NSTimeZone systemTimeZone]];
time = [dateFormatters1 stringFromDate: destinationDate];
convert = [[NSArray alloc ]initWithObjects:dateStr,time,nil];
return convert;
}
If you are sure that the string you need to parse is always formatted in that way, then regexes provide a simple way to do it:
NSString *str = #"2014-03-08T16:59+0000";
NSString *pattern = #"^.*T\\d{2}:\\d{2}";
NSString *timezone = [str stringByReplacingOccurrencesOfString: pattern
withString: #""
options: NSRegularExpressionSearch
range: NSMakeRange(0, str.length)];

NSString to NSDate return null value

Here i am getting current time and check whether its in am/pm format. If its not like that, i convert 24 hour time format into 12 hour time format and add AM/PM manually.
This is my code:
- (NSString *) getCurrentTime {
NSDate *today = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"hh:mm:ss a"];
NSString *currentTime = [timeFormatter stringFromDate:today];
currentTime = [self checkTimeFormat:currentTime];
return currentTime;
}
And
- (NSString *) checkTimeFormat:(NSString *) currentTime
{
NSArray *timeArray = [currentTime componentsSeparatedByString:#":"];
int intHour = [[timeArray objectAtIndex:0] intValue];
NSString *lastVal = [timeArray objectAtIndex:2];
if ([lastVal rangeOfString:#"M"].location == NSNotFound) {
if (intHour < 12)
lastVal = [NSString stringWithFormat:#"%# AM", [timeArray objectAtIndex:2]];
else
lastVal = [NSString stringWithFormat:#"%# PM", [timeArray objectAtIndex:2]];
}
if (intHour > 12)
intHour = intHour - 12;
currentTime = [NSString stringWithFormat:#"%d:%#:%#", intHour, [timeArray objectAtIndex:1], lastVal];
NSLog(#"Current Time ==>> %#", currentTime);
return currentTime;
}
Conversion of NSString into NSDate code below:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm:ss a"];
NSDate *testDate = [dateFormatter dateFromString:getCurrentTime];
NSLog(#"testDate => %#", testDate);
If the Time is in 12 hour format (am/pm), testDate value is getting correctly.
If the Time is in 24 hour format, testDate value is null
What is the issue?
Thanks in Advance.
You can try:
NSDate *today = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"HH:mm:ss"];
NSString *currentTime24 = [timeFormatter stringFromDate:today];
[timeFormatter setDateFormat:#"hh:mm:ss a];
NSDate *currentTime12 = [timeFormatter dateWithString:currentTime24];
NSString *currentTime = [timeFormatter stringWithDate:currentTime12];

Split a NSDate into day and time

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

Resources