Split NSDate into year month date - iphone

If I have a date like 04-30-2006
how can I split and get month, day and year
Alsois there any direct way of comparing the years ?

you have to use NSDateComponents. Like this:
NSDate *date = [NSDate date];
NSUInteger componentFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [[NSCalendar currentCalendar] components:componentFlags fromDate:date];
NSInteger year = [components year];
NSInteger month = [components month];
NSInteger day = [components day];
Alsois there any direct way of comparing the years ?
not built in. But you could write a category for it. Like this:
#interface NSDate (YearCompare)
- (BOOL)yearIsEqualToDate:(NSDate *)compareDate;
#end
#implementation NSDate (YearCompare)
- (BOOL)yearIsEqualToDate:(NSDate *)compareDate {
NSDateComponents *myComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:self];
NSDateComponents *otherComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:compareDate];
if ([myComponents year] == [otherComponents year]) {
return YES;
}
return NO;
}
#end

to split it is easy
NSString *dateStr = [[NSDate date] description];
NSString *fStr = (NSString *)[[dateStr componentsSeparatedByString:#" "]objectAtIndex:0];
NSString *y = (NSString *)[[fStr componentsSeparatedByString:#"-"]objectAtIndex:0];
NSString *m = (NSString *)[[fStr componentsSeparatedByString:#"-"]objectAtIndex:1];
NSString *d = (NSString *)[[fStr componentsSeparatedByString:#"-"]objectAtIndex:2];
this will be easy to get things what you want basically .

All the answers so far assume you have an actual NSDate object, but in your post you say, "I have a date like 04-30-2006" which could be a string. If it is a string then Abizem's answer is the closest to what you want:
NSString* dateString = #"04-30-2006";
NSArray* parts = [dateString componentsSeparatedByString: #"-"];
NSString* month = [parts objectAtIndex: 0];
NSString* day = [parts objectAtIndex: 1];
NSString* year = [parts objectAtIndex: 2];

Or, using NSDateFormatter:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *now = [NSDate date];
[formatter setDateFormat:#"MM"];
NSString *month = [formatter stringFromDate:now];
[formatter setDateFormat:#"dd"];
NSString *day = [formatter stringFromDate:now];
[formatter setDateFormat:#"yyyy"];
NSString *year = [formatter stringFromDate:now];
[formatter release];
(code typed right here; caveat implementor)

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

NSDateFormatter not working to set setTimeZone

I am trying to know the difference between two dates (Including days,hours,minutes and seconds). For that I am using below code, but It's not working.
+ (void)UpdateTableViewCellWithNSTimer:(NSString *)gameTime :(UIView *)inputView{
NSDate *now = [NSDate date];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setLocale:[NSLocale systemLocale]];
[outputFormatter setAMSymbol:#"AM"];
[outputFormatter setPMSymbol:#"PM"];
[outputFormatter setTimeZone:[NSTimeZone localTimeZone]];
[outputFormatter setDateFormat:#"mm/dd/yyyy hh:mm a"];
NSDate *gameDate = [outputFormatter dateFromString:gameTime];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:gameDate toDate:now options:0];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger seconds = [components second];
NSInteger minutes = [components minute];
UITableView *dynamicTable = (UITableView *)[inputView viewWithTag:55];
NSIndexPath *cellIndexPath = [NSIndexPath indexPathForRow:4 inSection:0];
UITableViewCell *currentCell = [dynamicTable cellForRowAtIndexPath:cellIndexPath];
NSString *challengeStartsIn=[NSString stringWithFormat:#"%01ddays:%02dhrs:%02dmins:%02dsec",abs(days),abs(hours), abs(minutes), abs(seconds)];
NSString *Mystring =[NSString stringWithFormat:#"%# %#", #"ChallengeStartsIn", challengeStartsIn];
currentCell.textLabel.text = Mystring;
}
**Game and now dates on logs are:**
2013-05-18 11:36:42.609 FPPresent[2213:5203] gametime value=05/19/2013 5:30 AM
2013-05-18 11:36:42.610 FPPresent[2213:5203] now=2013-05-18 06:06:42 +0000
After using outputformatter:
gametime value =2013-01-19 00:00:00 +0000(It should be 2013-01-19 05:30:00 +0000 )
now=2013-05-18 06:10:07 +0000(should be : 2013-05-18 11:40:07 +0000)
The game date and now date should in localTimeZone. But, even I try to set
[outputFormatter setTimeZone:[NSTimeZone localTimeZone]];
My data format is showing (Exactly 5.30 hours different, our local time zone is GMT+5.30)
Please let me know where I am going wrong
[NSDate date] is taking default timezone as GMT. so, I am unable to set my local timezone to date.
While knowing the difference between GMT OFFset to local , I am able to get the difference between two dates sucessfully.
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setAMSymbol:#"AM"];
[outputFormatter setPMSymbol:#"PM"];
[outputFormatter setLocale:[NSLocale currentLocale]];
[outputFormatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *gameDate = [outputFormatter dateFromString:gameTime];
NSDate* gameDestinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:gameDate];
// NSLog(#"gameDate=%#",gameDate);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:destinationDate toDate:gameDestinationDate options:0];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger seconds = [components second];
NSInteger minutes = [components minute];
return ([NSString stringWithFormat:#"%01ddays:%02dhrs:%02dmins:%02dsec",abs(days),abs(hours), abs(minutes), abs(seconds)]);
Are you setting the timeZone for the output formatter and along with that are you adding the time difference to the output date?? Because, there is not need to add the time difference as setting timezone for both dateFormatters will automatically take care of the time difference between the time zones.

Incrementing a date's year by one if that date has already passed

I have an array containing birth dates like the one below:
Array(
"11/07/2013",
"07/10/2013",
"20/02/2013"
)
Now I want to make a new array based on whether or not the date has passed. Writing this question in 2013, if a current date has passed then we will change that date's year to 2014. If it hasn't passed then we will have it stay the 2013 date.
For example:
NewArray(
"11/07/2013", no change cus this date hasnt passed yet
"07/10/2013", no change same as above
"20/02/2014" **as date has already passed thats why 2014**
I'm using the following code for this
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSString *curYear = [dateFormatter stringFromDate:[NSDate date]];
NSString *nextYear = [NSString stringWithFormat: #"%d", ([curYear intValue] + 1)];
for(int i = 0; i < [_newlymadeArray count]; i++)
{
NSString *dateStr = [_newlymadeArray objectAtIndex:i];
NSComparisonResult comResult = [[dateFormatter dateFromString:dateStr] compare: [NSDate date]];
if(comResult == NSOrderedAscending)
{
[dateStr stringByReplacingOccurrencesOfString:curYear withString:nextYear];
[_newlymadeArray replaceObjectAtIndex:i withObject:dateStr];
NSLog(#"_newlymadeArray%#",_newlymadeArray);
}
NSLog(#"_newlymadeArray%#",_newlymadeArray);
This is however what I get when I NSLog _newlymadeArray:
after replacing (
"11/07/2013",
"07/10/2013",
"20/02/2013"
)
At index 2 it should be "20/02/2014" instead of the 2013 date. What might cause my problem and how can I solve it?
I've made some modifications to your code, and it is working as you want.
In my code I've compared date, which is in Ascending form of current date. If it satisfies the condition, then I've fetched YEAR from matched date, by the DateFormatter "yyyy". Then I simply increment this year by 1, and replace this year in old Date, which is "20/02/2013" to "20/02/2014"
array = [[NSMutableArray alloc] initWithObjects:#"11/07/2013",#"07/10/2013",#"20/02/2013", nil];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
for(int i = 0; i < [array count]; i++)
{
NSString *dateStr = [array objectAtIndex:i];
NSComparisonResult comResult = [[dateFormatter dateFromString:dateStr] compare: [NSDate date]];
if(comResult == NSOrderedAscending)
{
NSDateFormatter *yrFormatter = [[NSDateFormatter alloc] init];
[yrFormatter setDateFormat:#"yyyy"];
NSString *curYear = [yrFormatter stringFromDate:[NSDate date]];
NSString *nextYear = [NSString stringWithFormat: #"%d", ([curYear intValue] + 1)];
NSLog(#"%#",curYear);
NSLog(#"%#",nextYear);
dateStr = [dateStr stringByReplacingOccurrencesOfString:curYear withString:nextYear];
NSLog(#"%#",dateStr);
[array replaceObjectAtIndex:i withObject:dateStr];
NSLog(#"_newlymadeArray%#",array);
}
NSLog(#"_newlymadeArray%#",array);
}
This seems to be working perfectly, so I hope it helps you.
Plese dear try to use this one.I think this one may help
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [[NSDateComponents alloc] init];
components.year = 1;
NSDate* newDate = [calendar dateByAddingComponents: components toDate:#"YourDate" options: 0];
Otherwise you can use this one code.
if (comResult == NSOrderedSame)
{
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [[NSDateComponents alloc] init];
components.year = 1;
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"dd/MM/yyyy"];
NSDate *date = [formatter dateFromString:#"11/07/2013"];
NSDate* newDate = [calendar dateByAddingComponents: components toDate:date options: 0];
// here replace your array object with this "newDate"
}
Compare your array date to today's date with NSDate compare function. Here are the details:
NSString *arrayDateString = #"20/02/2013" // fetch this string from your array
NSDate *todaysDate = [NSDate date];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/MM/yyyy"];
NSDate* d = [df dateFromString:arrayDateString];
// now compare this date (d) with todaysDate using NSDate function
if ([d compare:todaysdate]== NSOrderedAscending)
{//write your code here}
If it results NSOrderedAscending, then it means array date is earlier than today's date.
So for that date, update year incremented by one using NSDateComponents:
NSDateComponents *dayComponent = [[[NSDateComponents alloc] init] autorelease];
dayComponent.year = 1;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
dateToBeIncremented = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];
Or you can use NSDate function itself:
NSDate *now = arrayDate;
int yearsToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*365*year];
But second option is not full-proof - because of leap year problem.
Hope this two options help you, for solving your issue.
NSArray * array = [[NSArray alloc] initWithObjects:#"11/07/2013",#"07/10/2013",#"20/02/2013", nil];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
NSMutableArray *output = [NSMutableArray new];
for(int i = 0; i < [array count]; i++)
{
NSString *dateStr = [array objectAtIndex:i];
NSDate *date = [dateFormatter dateFromString:dateStr];
if ([date compare:now] == NSOrderedAscending)
{
[components setYear:1];
date = [calendar dateByAddingComponents:components toDate:date options:0];
}
dateStr = [dateFormatter stringFromDate:date];
[output addObject:dateStr];
}
NSLog(#"Result : %#",output);

How can we set date in to date picker with string in a format like 12:30 AM?

Hello Everybody I want set date in to datepicker from string like above format given in the question
I m using following code to set date to datepicker
NSString *tmStr=[selectedDics objectForKey:#"Time"];
NSArray *timeStr=[tmStr componentsSeparatedByString:#" "];
NSString *fStr=[timeStr objectAtIndex:1];
NSArray *Time=[[timeStr objectAtIndex:0]componentsSeparatedByString:#":"];
NSInteger hour=[[Time objectAtIndex:0] intValue];
NSString *str=[NSString stringWithFormat:#"%i:%i",hour,[[Time objectAtIndex:1]intValue]];
NSString *a;
if ([fStr isEqualToString:#"PM"])
{
a=#"PM";
hour=hour+12;
}else
{
a=#"AM";
if (hour==12) {
hour=0;
}
}
NSCalendar *calender = [NSCalendar currentCalendar];
[calender setTimeZone:[NSTimeZone defaultTimeZone]];
unsigned currentFlag = NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *comps = [calender components:currentFlag fromDate:[NSDate date]];
comps.hour = hour;
comps.minute = [[Time objectAtIndex:1]intValue];
datePicker.date = [calender dateFromComponents:comps];
Is there another way to set it easily?
NSDateFormatter *formatter;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"h:mm a"];
NSDate *date=[formatter dateFromString:#"12:30 AM"];
[datepicker setDate:date];

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