iPhone: Date conversion issues - iphone

I need to check an event date, which should be between Current date and 60 days from now. The below code is used, but it is NOT working correctly. Please note, i'm getting event string like this - "2012-04-14T16:50:02Z" from my server.
// current date
double currDateInMilliSecs = [NSDate timeIntervalSinceReferenceDate] * 1000;
NSLog(#"currDateInMilliSecs: %f", currDateInMilliSecs);
// sixty days
double sixtydaysvalue = 60.0 * 24.0 * 3600.0 * 1000.0;
NSLog(#"sixtydaysvalue: %f", sixtydaysvalue);
// add current date + sixt days
double sixtyDaysMilliSecsFromCurrDate = currDateInMilliSecs + sixtydaysvalue;
NSLog(#"sixtyDaysMilliSecsFromCurrDate: %f", sixtyDaysMilliSecsFromCurrDate);
// check does the event date between current date + 60 days
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//[df setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[df setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
//[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
// [eventDict objectForKey:#"begin_at"] gives date string like this "2012-04-14T16:50:02Z" for ex.
NSDate *eventdate = [df dateFromString:[eventDict objectForKey:#"begin_at"]];
NSTimeInterval nowSinceEventDate = [eventdate timeIntervalSince1970];
NSLog(#"nowSinceEventDate: %f", nowSinceEventDate);
double eventDateInMilliSecs = nowSinceEventDate * 1000;
NSLog(#"eventDateInMilliSecs: %f", eventDateInMilliSecs);
// this is not working as expected
if ( eventDateInMilliSecs<sixtyDaysMilliSecsFromCurrDate && eventDateInMilliSecs>currDateInMilliSecs )
{
}
else
{
}
Any help please?

try this
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss SSS"];

Try this:
NSString *dateString = #"2012-04-14T16:50:02Z";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *eventDate = [formatter dateFromString:dateString];
NSTimeInterval nowSinceEventDate = [eventDate timeIntervalSince1970];
NSLog(#"interval = %f", nowSinceEventDate);
UPDATE:
NSString *dateString = #"2012-05-21T16:50:02Z";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *eventDate = [formatter dateFromString:dateString];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:60];
NSDate *minDate = [NSDate date];
NSDate *maxDate = [gregorian dateByAddingComponents:components toDate:minDate options:0];
NSLog(#"eventDate interval = %f", [eventDate timeIntervalSince1970]);
NSLog(#"minDate interval = %f", [minDate timeIntervalSince1970]);
NSLog(#"maxDate interval = %f", [maxDate timeIntervalSince1970]);
BOOL isBetween = (([eventDate compare:minDate] == NSOrderedDescending) && ([eventDate compare:maxDate] == NSOrderedAscending));
NSLog(#"isBetween = %d", isBetween);

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss:SSS"];
// [eventDict objectForKey:#"begin_at"] gives "2012-04-14T16:50:02Z"
NSDate *eventdate = [df dateFromString:[eventDict objectForKey:#"begin_at"]];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
SSS for milli seconds

Related

How to get current year first date in iphone programmatically

Am working in iphone application, Now i want to get current year and current month first date from current date.
For (e.x: First date of year : 2013/01/01)
And (e.x first date of month is: 2013/12/01)
Please help me to out of this issue. Thanks.
// This is your currentDate
NSDate *today = [NSDate date];
// NSDateFormatter to separate the Year and Month from currentDate
NSDateFormatter *df = [[NSDateFormatter alloc] init]
[df setDateFormat:#"yyyy"];
NSInteger currentYear = [[df stringFromDate:today] integerValue];
NSString *currentYearFirstDate = [NSString stringWithFormat:#"%d/01/01", currentYear];
[df setDateFormat:#"MM"];
NSInteger currentMonth = [[df stringFromDate:today] integerValue];
NSString *currentMonthFirstDate = [NSString stringWithFormat:#"%d/%d/01", currentYear, currentMonth];
// You can get date object from above string via using below date format
[df setDateFormat:#"yyyy/MM/dd"];
NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
[components setDay:1];
self.currentDate = [calendar dateFromComponents:components];
int m = components.month;
int y = components.year;
int d = components.day;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy MM dd"];
NSDate *firstDateOfMonth = [df dateFromString:[NSString stringWithFormat:#"%d %d 01",y,m]];
NSDate *firstDateOfYear = [df dateFromString:[NSString stringWithFormat:#"%d 01 01",y]];

ios: String to Date conversion

I am trying to convert my date from NSString to NSDate using following code
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
[dateformatter setTimeStyle:NSDateFormatterNoStyle];
[dateformatter setDateFormat:#"dd/MM/yyyy"];
NSDate *myDate = [[NSDate alloc] init];
currMonth = 3;
currYear = 2012;
NSString *str = [NSString stringWithFormat:#"01/%2d/%d", currMonth, currYear];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"0"];
myDate = [dateformatter dateFromString:str];
NSLog(#"myStr: %#",str);
NSLog(#"myMonth: %2d",currMonth);
NSLog(#"myYear: %d",currYear);
NSLog(#"myDate: %#",myDate);
Above code is giving me wrong date. Can anyone please help?
What is your output? Keep in mind, that NSDate is in UTC.
2012-03-01 00:00:00 (GMT+1) is 2012-02-39 23:00:00 (UTC)
Another tip:
%02 formats your integers with leading zeros.
Try this:
-(NSDate *)dateFromString:(NSString *)string
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormat setLocale:locale];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSTimeInterval interval = 5 * 60 * 60;
NSDate *date1 = [dateFormat dateFromString:string];
date1 = [date1 dateByAddingTimeInterval:interval];
if(!date1) date1= [NSDate date];
[dateFormat release];
[locale release];
return date1;
}
Tell me if it helps u :]
try
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
[dateformatter setTimeStyle:NSDateFormatterNoStyle];
[dateformatter setDateFormat:#"dd/MM/yyyy"];
NSDate *myDate = [[NSDate alloc] init];
int currMonth = 3;
int currYear = 2012;
NSString *str = [NSString stringWithFormat:#"01/%2d/%d", currMonth, currYear];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"0"];
//SET YOUT TIMEZONE HERE
dateformatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"PDT"];
myDate = [dateformatter dateFromString:str];
NSLog(#"myStr: %#",str);
NSLog(#"myMonth: %2d",currMonth);
NSLog(#"myYear: %d",currYear);
NSLog(#"myDate: %#",myDate);

Splitting time to 10 mins interval in iphone

i want to split the time in the interval of 30mins, so i can get time like this:
12:00 AM 12:10 AM 12:20 AM .......... till 11:50 PM.
i'm trying something like this :
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"hh:mm a"];
NSDate* fromTime = [timeFormat dateFromString:startTime];
NSDate* toTime = [timeFormat dateFromString:endTime];
NSLog(#"Start time %#",fromTime);
NSLog(#"End time %#",toTime);
NSDate *dateByAddingThirtyMinute;
dateByAddingThirtyMinute = [fromTime dateByAddingTimeInterval:1800];
NSString *formattedDateString;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
formattedDateString = [dateFormatter stringFromDate:dateByAddingThirtyMinute];
NSLog(#"Time after 10 min %#",formattedDateString);
but i am able to print the first ten minute splitting ...
can any one help me how to loop it ...
Both of the other answers are wrong, because they do not account for daylight savings time. To do that, you have to use NSDateComponents and NSCalendar:
NSDate *startDate = ...;
NSDate *endDate = ...;
NSDateComponents *diff = [[NSDateComponents alloc] init];
[diff setMinute:0];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *tmp = startDate;
NSMutableArray *dates = [NSMutableArray arrayWithObject:tmp];
while ([tmp laterDate:endDate] == endDate) {
[diff setMinute:[diff minute] + 10];
tmp = [cal dateByAddingComponents:diff toDate:startDate options:0];
[dates addObject:tmp];
}
In this code, I'm not actually running the NSDate objects through the NSDateFormatter, because that should happen at a different level. This code is all about the underlying data (the Model), and NSDateFormatter usually operates at the user-visible level (the View). Plus, it's generally more useful to have the raw data object than the formatted string.
Try with below code
NSString *startTime = #"12:00 AM";
NSString *endTime = #"11:40 AM";
NSDateFormatter *timeFormat = [[[NSDateFormatter alloc] init] autorelease];
[timeFormat setDateFormat:#"hh:mm a"];
NSDate* fromTime = [timeFormat dateFromString:startTime];
NSDate* toTime = [timeFormat dateFromString:endTime];
NSDate *dateByAddingThirtyMinute ;
NSTimeInterval timeinterval = [toTime timeIntervalSinceDate:fromTime];
NSLog(#"time Int %f",timeinterval/3600);
float numberOfIntervals = timeinterval/3600;
NSLog(#"Start time %f",numberOfIntervals);
for(int iCount = 0;iCount<numberOfIntervals*6 ;iCount ++)
{
dateByAddingThirtyMinute = [fromTime dateByAddingTimeInterval:600];
fromTime = dateByAddingThirtyMinute;
NSString *formattedDateString;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"hh:mm a"];
formattedDateString = [dateFormatter stringFromDate:dateByAddingThirtyMinute];
NSLog(#"Time after 10 min %#",formattedDateString);
}
Try this out
int numberOfIntervals = [toDate timeIntervalSinceDate:fromDate]/(10*60);
for (int i = 0; i < numberOfIntervals; i++) {
NSDate *theDate = [date dateByAddingTimeInterval:i * 60 * 10];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
NSString *formattedDateString = [dateFormatter stringFromDate:dateByAddingThirtyMinute];
NSLog(#"Time after 10 min %#",formattedDateString);
[dateFormatter release];
}

convert string into NSDate

i have a "DateTimeArray" this array contain
DateTimeArray[index 0] = 20.05.2011 12:12:50
DateTimeArray[index 1]= 20.05.2011 12:13:20
DateTimeArray[index 2]= 20.05.2011 12:20:10
all the value are in string,and i want to convert this string into NSDate and only want to access time not date
and then this time values will be stored in array and this newly array will be used for drawing line chart
i hope some one know this issue
thank you very much
Code as follows,
for(int index=0;index<[DateTimeArray count];index++)
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm:ss"];
NSString *timeString=[[[DateTimeArray objectAtIndex:index]componentsSeparatedByString:#" "]objectAtIndex:1];
NSDate *time=[df dateFromString:timeString];
[timeArray addObject:time];
[df release];
}
Try this
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm:ss"];
NSDate *formattedDate = [df dateFromString:[DateTimeArray objectAtIndex:requiredIndex]];
[df release];
Best and cleaner approach:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd.MM.yyyy HH:mm:ss"];
for(int i=0; i < [DateTimeArray count]; ++i)
{
NSString *string = [DateTimeArray objectAtIndex:i];
NSDate *date = [df dateFromString:string];
[timeArray addObject:time];
}
[df release]; // ALWAYS release unused objects
Then to just access hours, and not days, you should select the required components of each NSDate* instance:
// Get the Gregorian calendar
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Get the date
NSDate* date = [timeArray objectAtIndex:my_index];
// Get the hours, minutes, seconds
NSDateComponents* hour = [cal components:NSHourCalendarUnit fromDate:date];
NSDateComponents* minute = [cal components:NSMinuteCalendarUnit fromDate:date];
NSDateComponents* second = [cal components:NSSecondCalendarUnit fromDate:date];
NSMutableArray *nsdateArray = [NSMutableArray arrayWithCapacity:[DateTimeArray count]];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd.MM.yyyy HH:mm:ss"];
for(NSString *currentString in DateTimeArray){
NSDate *date = [dateFormat dateFromString:currentString];
[nsdateArray addObject:date];
}
[dateFormat release];
NSLog(#"ArrayWithDate:%#",[nsdateArray description]);
Heres the complete set of code.. Hope it helps..
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
int i=0;//start for{} loop
NSString *currDate = [formatter dateFromString:[DateTimeArray objectAtIndex:i]];
[formatter release];
Happy iCoding...
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm:ss"]
NSString *theTime = [timeFormat dateFromString:date];
or
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(kCFCalendarUnitHour | kCFCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];

iPhone: NSDate convert GMT to local time

I currently have an API call returning me a date/time in the format: 2010-10-10T07:54:01.878926
Can I assume this is GMT? I also converted this to an NSDate object. Is there a way to use the local iPhone time to recalculate the time?
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm";
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];
This code will convert the GMT time to the device's local time.
NSDate* localDateTime = [NSDate dateWithTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMT] sinceDate:pubDate];
NSDate *sourceDate = [NSDate dateWithTimeIntervalSince1970:gmtTimestamp];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [destinationTimeZone secondsFromGMTForDate:0];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm";
[dateFormatter setTimeZone:destinationTimeZone];
NSString *localTimeString = [dateFormatter stringFromDate:destinationDate];
NSDate *now = [NSDate date];
NSLog(#"%#", [now dateWithCalendarFormat:#"%Y-%m-%d %H:%M:%S"
timeZone:[NSTimeZone timeZoneWithName:#"GMT"]]);