Format date on iPhone returns (null) - iphone

I have a date with the format:
Fri Jul 16 16:58:46 +0000 2010.
To convert it to Fri Jul 16 2010 I tried:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
for(int i=0; i<[self.data count]; i++) {
id celldata = [self.data objectAtIndex:i];
NSString *str = [NSString stringWithFormat:#"%#", [celldata objectForKey:#"created_at"]];
NSLog(#"date for %u is %#",i, str); //this works and writes the date
[df setDateFormat:#"eee MMM dd HH:mm:ss Z yyyy"];
NSDate *date = [df dateFromString:str];
[df setDateFormat:#"eee MMM dd yyyy"];
NSString *dateStr = [df stringFromDate:date];
NSLog(#"%#",dateStr);
}
But NSLog(#"%#",dateStr) only writes (null). How to get it working?
EDIT
For whatever reason I got it working by changing
[df setDateFormat:#"eee MMM dd HH:mm:ss Z yyyy"];
to
[df setDateFormat:#"MMM dd HH:mm:ss Z yyyy"];
and deleting the week day from my string. However, thank you all.

This might help you out a bit. I had a similar problem a while back, so I created the following methods.
Definitions
#define DATE_TYPE_hhmmss [NSArray arrayWithObjects:#"h", #"m", #"s", nil]
#define DATE_TYPE_MMDDYYYY [NSArray arrayWithObjects:#"M", #"D", #"Y", nil]
#define DATE_TYPE_MMDDYYYYhhmmss [NSArray arrayWithObjects:#"M", #"D", #"Y", #"h", #"m", #"s", nil]
#define DATE_TYPE_MMDDYYYYWWhhmmss [NSArray arrayWithObjects:#"M", #"D", #"Y", #"W", #"h", #"m", #"s", nil]
#define DATE_TYPE_MMDDYYYYhhmmssWW [NSArray arrayWithObjects:#"M", #"D", #"Y", #"h", #"m", #"s", #"W", nil]
#define DATE_TYPE_YYYYMMDD [NSArray arrayWithObjects:#"Y", #"M", #"D", nil]
#define DATE_TYPE_YYYYMMDDhhmmss [NSArray arrayWithObjects:#"Y", #"M", #"D", #"h", #"m", #"s", nil]
#define DATE_TYPE_YYYYMMDDWWhhmmss [NSArray arrayWithObjects:#"Y", #"M", #"D", #"W", #"h", #"m", #"s", nil]
#define DATE_TYPE_YYYYMMDDhhmmssWW [NSArray arrayWithObjects:#"Y", #"M", #"D", #"h", #"m", #"s", #"W", nil]
#define DATE_TYPE_FRIENDLY [NSArray arrayWithObjects:#"xx", nil]
Date Methods
Create Date From Values
-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year {
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMonth:month];
[dateFormatter setDateFormat:#"DD"];
[dateComponents setDay:day];
[dateFormatter setDateFormat:#"YYYY"];
[dateComponents setYear:year];
NSDate * result = [calendar dateFromComponents:dateComponents];
return result;
}
-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year hour:(int)hour minute:(int)minute {
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMonth:month];
[dateFormatter setDateFormat:#"DD"];
[dateComponents setDay:day];
[dateFormatter setDateFormat:#"YYYY"];
[dateComponents setYear:year];
[dateFormatter setDateFormat:#"HH"];
[dateComponents setHour:hour];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMinute:minute];
NSDate * result = [calendar dateFromComponents:dateComponents];
return result;
}
-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year hour:(int)hour minute:(int)minute second:(int)second {
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMonth:month];
[dateFormatter setDateFormat:#"DD"];
[dateComponents setDay:day];
[dateFormatter setDateFormat:#"YYYY"];
[dateComponents setYear:year];
[dateFormatter setDateFormat:#"HH"];
[dateComponents setHour:hour];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMinute:minute];
[dateFormatter setDateFormat:#"SS"];
[dateComponents setSecond:second];
NSDate * result = [calendar dateFromComponents:dateComponents];
return result;
}
Get String From Date
-(NSString *) getStringFromDate:(NSDate *)date dateType:(NSArray *)dateType {
NSString * result = #"";
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSString * format = #"";
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger weekday = [dateComponents weekday];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
if (dateType != nil) {
for (int x = 0; x < [dateType count]; x++) {
if (x == ([dateType count]-1)) {
if ([[dateType objectAtIndex:x] isEqualToString:#"Y"]) {
format = [format stringByAppendingFormat:#"%d", year];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"M"]) {
format = [format stringByAppendingFormat:#"%d", month];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"D"]) {
format = [format stringByAppendingFormat:#"%d", day];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"W"]) {
format = [format stringByAppendingFormat:#"%d", weekday];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"h"]) {
format = [format stringByAppendingFormat:#"%d", hour];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"m"]) {
format = [format stringByAppendingFormat:#"%d", minute];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"s"]) {
format = [format stringByAppendingFormat:#"%d", second];
}
} else {
if ([[dateType objectAtIndex:x] isEqualToString:#"Y"]) {
format = [format stringByAppendingFormat:#"%d|", year];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"M"]) {
format = [format stringByAppendingFormat:#"%d|", month];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"D"]) {
format = [format stringByAppendingFormat:#"%d|", day];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"W"]) {
format = [format stringByAppendingFormat:#"%d|", weekday];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"h"]) {
format = [format stringByAppendingFormat:#"%d|", hour];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"m"]) {
format = [format stringByAppendingFormat:#"%d|", minute];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"s"]) {
format = [format stringByAppendingFormat:#"%d|", second];
}
}
if ([[dateType objectAtIndex:x] isEqualToString:#"xx"]) {
format = [NSString stringWithFormat:#"Year: %d, Month: %d, Day: %d, Weekday: %d, Hour: %d, Minute: %d, Second: %d", year, month, day, weekday, hour, minute, second];
}
}
} else {
format = [format stringByAppendingFormat:#"%d|", year];
format = [format stringByAppendingFormat:#"%d|", month];
format = [format stringByAppendingFormat:#"%d|", day];
format = [format stringByAppendingFormat:#"%d|", weekday];
format = [format stringByAppendingFormat:#"%d|", hour];
format = [format stringByAppendingFormat:#"%d|", minute];
format = [format stringByAppendingFormat:#"%d|", second];
format = [NSString stringWithFormat:#"%d|%d|%d|%d|%d|%d|%d", year, month, day, weekday, hour, minute, second];
}
result = format;
return result;
}
Example
NSDate * date = [self getDateWithMonth:12 day:24 year:1994];
NSString * dateInString = [self getStringFromDate:date dateType:DATE_TYPE_MMDDYYYY];
int month = [[[dateInString componentsSeparatedByString:#"|"] objectAtIndex:0] intValue];
int day = [[[dateInString componentsSeparatedByString:#"|"] objectAtIndex:1] intValue];
int year = [[[dateInString componentsSeparatedByString:#"|"] objectAtIndex:2] intValue];
NSLog(#"String of Date: \"%#\"", dateInString);
NSLog(#"Month: %d", month);
NSLog(#"Day: %d", day);
NSLog(#"Year: %d", year);
The method [self getDateWithMonth:12 day:24 year:1994] returns an NSDate object which is usually hard to read, so you can use [self getStringFromDate:date dateType:DATE_TYPE_MMDDYYYY] to get a string of an NSDate object.
Use the definitions (macros) to specify the format of the date you would like to get in the string.
For example:
DATE_TYPE_hhmmss would return the Hour|Minute|Second,
DATE_TYPE_MMDDYYYY would return the Month|Day|Year,
DATE_TYPE_MMDDYYYYhhmmss would return the Month|Day|Year|Hour|Minute|Second,
DATE_TYPE_MMDDYYYYWWhhmmss would return the Month|Day|Year|Weekday (#)|Hour|Minute|Second
and so on...
Console Log
2012-04-29 13:42:15.791 Atomic Class[1373:f803] String of Date: "12|24|1994"
2012-04-29 13:42:15.793 Atomic Class[1373:f803] Month: 12
2012-04-29 13:42:15.794 Atomic Class[1373:f803] Day: 24
2012-04-29 13:42:15.794 Atomic Class[1373:f803] Year: 1994

If the original strings you are parsing to dates are really in the format of "20081122" then the first call to "setDateFormat" is incorrect in both snippets, as the format of the specified is incorrect.
Assuming that [celldata objectForKey:#"created_at"] is returning dates in the format of "20081122" per your second code snippet, you need to change the first call to setDateFormat to use the correct format for the string, "yyyyMMdd" This will drive a correct conversion when you call the method "dateFromString" Then, once you have a NSDate* object representation, you can use whatever format you need when you convert it back to a string via stringFromDate.
NSString *dateStr = #"20081122";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
//This is the important change here, this format MUST match the format of the string.
[dateFormat setDateFormat:#"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat setDateFormat:#"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
[dateFormat release];

Use Dateformatter for week EEE instead of eee
[df setDateFormat:#"EEE MMM dd HH:mm:ss Z yyyy"];
I hope this will be helpful to you...

Related

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.

How to get the number of weeks in a month

Here is the problem, i'm looking for a way to get the number of weeks in a month. I already find a solution that seems to work on ios 5, but it not on io6 (number returned is not the same, one more on ios 6).
- (int)weeksOfMonth:(int)month inYear:(int)year
{
NSCalendar *cCalendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setMonth:month];
[components setYear:year];
NSRange range = [cCalendar rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:[cCalendar dateFromComponents:components]];
cCalendar = [NSCalendar currentCalendar];
[cCalendar setMinimumDaysInFirstWeek:4];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setLocale: [[NSLocale alloc] initWithLocaleIdentifier:#"fr"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSMutableSet *weeks = [[NSMutableSet alloc] init ];
for(int i = 0; i < range.length; i++)
{
NSString *temp = [NSString stringWithFormat:#"%4d-%2d- %2d",year,month,range.location+i];
NSDate *date = [dateFormatter dateFromString:temp ];
int week = [[cCalendar components: NSWeekOfYearCalendarUnit fromDate:date] weekOfYear];
[weeks addObject:[NSNumber numberWithInt:week]];
}
return [weeks count];
}
The returned value is 6 on io6 and 5 on io5.
Do you have any idea ?
EDIT : Another thing, my device (ios5) is in French and the simulator (ios6) is in English. Maybe it can change something (like the first day of week ?) ?
Try this one :
NSDate *date = [NSDate date];//since you are forming date, put it here
NSCalendar *calender = [NSCalendar currentCalendar];
NSRange weekRange = [calender rangeOfUnit:NSWeekCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
NSInteger weeksCount=weekRange.length;
NSLog(#"%d",weeksCount);
Swift 4.0:
let date = Date()
let calendar = Calendar.current
let weekRange = calendar.range(of: .weekOfMonth,
in: .month,
for: date)
let weeksCount = weekRange.count ?? 0
print(weeksCount)
Or change your method to :
- (NSInteger)weeksOfMonth:(int)month inYear:(int)year{
NSString *dateString=[NSString stringWithFormat:#"%4d/%d/1",year,month];
NSDateFormatter *dfMMddyyyy=[NSDateFormatter new];
[dfMMddyyyy setDateFormat:#"yyyy/MM/dd"];
NSDate *date=[dfMMddyyyy dateFromString:dateString];
NSCalendar *calender = [NSCalendar currentCalendar];
NSRange weekRange = [calender rangeOfUnit:NSWeekCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
NSInteger weeksCount=weekRange.length;
return weeksCount;
}
EDIT:
use this in above method
//NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calender setFirstWeekday:2]; //sunday=1, monday=2 etc
Check this approach.
-(NSArray*)getWeekDaysForDate {
int dayOfWeek = [self weekDay];
NSMutableArray *array = [NSMutableArray array];
NSDate *weekStartDate = [self offsetDay:1-dayOfWeek];
NSCalendar *calendar = [NSCalendar defaultCalendar];
NSInteger monthValue = [self month];
unsigned int weekNum = [[calendar components: NSWeekCalendarUnit
fromDate: weekStartDate] week];
NSDate * nextDate = weekStartDate, *curDate;
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay:1];
unsigned int newWeekNum;
do {
curDate = nextDate;
nextDate = [calendar dateByAddingComponents:oneDay toDate: curDate
options:0];
newWeekNum = [[calendar components: NSWeekCalendarUnit fromDate:
nextDate] week];
int monthValueForNextDate = [[calendar components: NSMonthCalendarUnit fromDate:
nextDate] month];
if(monthValue == monthValueForNextDate)
[array addObject:nextDate]];
} while (newWeekNum == weekNum);
[array sortUsingSelector:#selector(compare:)];
return array;
}
-(int)month {
NSCalendar *gregorian = [NSCalendar defaultCalendar];
NSDateComponents *components = [gregorian components:NSMonthCalendarUnit fromDate:self];
return [components month];
}
-(int)weekDay {
NSCalendar *gregorian = [NSCalendar defaultCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit fromDate:self];
return [components weekday];
}
-(NSDate *)offsetDay:(int)numDays {
NSCalendar *gregorian = [NSCalendar defaultCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:numDays];
return [gregorian dateByAddingComponents:offsetComponents
toDate:self options:0];
}
PS: NSCalendar defaultCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
Adding this method then the category of NSDate will return the weekdays of any date that lies in the same week.
Best Regards.

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

Split NSDate into year month date

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)

How to get the day component out of an NSDate?

I have an NSDate object and need an integer of the day. i.e. if we have 25th May 2010, the int should be 25. Is there a simple way to do it?
Please consider this post on how to get calendar components from an NSDate. Essentially it will look something like:
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents* components = [calendar components:NSDayCalendarUnit
fromDate:myDate];
NSInteger day = [components day];
(Don't forget memory management for the above.)
If you only need the "25" part of an NSDate you can get it from a dateFormatter.
Something like:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd"];
NSString *dayInMonthStr = [dateFormatter stringFromDate:today];
int dayInMonth = [dayInMonthStr intValue];
[dateFormatter release];
NSLog(#"Today is the %i. day of the month", dayInMonth);
Note that an NSDate is just a timestamp and only has a "day" when considered with respect to a given calendar and time zone. If you want the Gregorian calendar in the current time zone,
NSTimeZone * tz = [NSTimeZone localTimeZone];
CFAbsoluteTime at = CFDateGetAbsoluteTime((CFDateRef)date);
int day = CFAbsoluteTimeGetGregorianDate(at, (CFTimeZoneRef)tz).day;
If you want the UTC day, set tz = nil.
Also, CFAbsoluteTime and NSDate are (as far as I know) based on POSIX time which specifies a 86400-second day, and thus do not handle leap seconds.
Use "EEEE" as the format for full name of the day.
Use "EEE" as the format for the short name of the day.
Example :
- (NSString *)getDayOfTheWeek:(NSDate *)date{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init] ;
[dateFormatter setDateFormat:#"EEEE"];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
return formattedDateString;
}
I had this problem a while back, and I created the following methods to make everything easier.
Definitions
#define DATE_TYPE_hhmmss [NSArray arrayWithObjects:#"h", #"m", #"s", nil]
#define DATE_TYPE_MMDDYYYY [NSArray arrayWithObjects:#"M", #"D", #"Y", nil]
#define DATE_TYPE_MMDDYYYYhhmmss [NSArray arrayWithObjects:#"M", #"D", #"Y", #"h", #"m", #"s", nil]
#define DATE_TYPE_MMDDYYYYWWhhmmss [NSArray arrayWithObjects:#"M", #"D", #"Y", #"W", #"h", #"m", #"s", nil]
#define DATE_TYPE_MMDDYYYYhhmmssWW [NSArray arrayWithObjects:#"M", #"D", #"Y", #"h", #"m", #"s", #"W", nil]
#define DATE_TYPE_YYYYMMDD [NSArray arrayWithObjects:#"Y", #"M", #"D", nil]
#define DATE_TYPE_YYYYMMDDhhmmss [NSArray arrayWithObjects:#"Y", #"M", #"D", #"h", #"m", #"s", nil]
#define DATE_TYPE_YYYYMMDDWWhhmmss [NSArray arrayWithObjects:#"Y", #"M", #"D", #"W", #"h", #"m", #"s", nil]
#define DATE_TYPE_YYYYMMDDhhmmssWW [NSArray arrayWithObjects:#"Y", #"M", #"D", #"h", #"m", #"s", #"W", nil]
#define DATE_TYPE_FRIENDLY [NSArray arrayWithObjects:#"xx", nil]
Date Methods
Create Date From Values
-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year {
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMonth:month];
[dateFormatter setDateFormat:#"DD"];
[dateComponents setDay:day];
[dateFormatter setDateFormat:#"YYYY"];
[dateComponents setYear:year];
NSDate * result = [calendar dateFromComponents:dateComponents];
return result;
}
-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year hour:(int)hour minute:(int)minute {
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMonth:month];
[dateFormatter setDateFormat:#"DD"];
[dateComponents setDay:day];
[dateFormatter setDateFormat:#"YYYY"];
[dateComponents setYear:year];
[dateFormatter setDateFormat:#"HH"];
[dateComponents setHour:hour];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMinute:minute];
NSDate * result = [calendar dateFromComponents:dateComponents];
return result;
}
-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year hour:(int)hour minute:(int)minute second:(int)second {
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMonth:month];
[dateFormatter setDateFormat:#"DD"];
[dateComponents setDay:day];
[dateFormatter setDateFormat:#"YYYY"];
[dateComponents setYear:year];
[dateFormatter setDateFormat:#"HH"];
[dateComponents setHour:hour];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMinute:minute];
[dateFormatter setDateFormat:#"SS"];
[dateComponents setSecond:second];
NSDate * result = [calendar dateFromComponents:dateComponents];
return result;
}
Get String From Date
-(NSString *) getStringFromDate:(NSDate *)date dateType:(NSArray *)dateType {
NSString * result = #"";
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSString * format = #"";
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger weekday = [dateComponents weekday];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
if (dateType != nil) {
for (int x = 0; x < [dateType count]; x++) {
if (x == ([dateType count]-1)) {
if ([[dateType objectAtIndex:x] isEqualToString:#"Y"]) {
format = [format stringByAppendingFormat:#"%d", year];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"M"]) {
format = [format stringByAppendingFormat:#"%d", month];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"D"]) {
format = [format stringByAppendingFormat:#"%d", day];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"W"]) {
format = [format stringByAppendingFormat:#"%d", weekday];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"h"]) {
format = [format stringByAppendingFormat:#"%d", hour];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"m"]) {
format = [format stringByAppendingFormat:#"%d", minute];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"s"]) {
format = [format stringByAppendingFormat:#"%d", second];
}
} else {
if ([[dateType objectAtIndex:x] isEqualToString:#"Y"]) {
format = [format stringByAppendingFormat:#"%d|", year];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"M"]) {
format = [format stringByAppendingFormat:#"%d|", month];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"D"]) {
format = [format stringByAppendingFormat:#"%d|", day];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"W"]) {
format = [format stringByAppendingFormat:#"%d|", weekday];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"h"]) {
format = [format stringByAppendingFormat:#"%d|", hour];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"m"]) {
format = [format stringByAppendingFormat:#"%d|", minute];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"s"]) {
format = [format stringByAppendingFormat:#"%d|", second];
}
}
if ([[dateType objectAtIndex:x] isEqualToString:#"xx"]) {
format = [NSString stringWithFormat:#"Year: %d, Month: %d, Day: %d, Weekday: %d, Hour: %d, Minute: %d, Second: %d", year, month, day, weekday, hour, minute, second];
}
}
} else {
format = [format stringByAppendingFormat:#"%d|", year];
format = [format stringByAppendingFormat:#"%d|", month];
format = [format stringByAppendingFormat:#"%d|", day];
format = [format stringByAppendingFormat:#"%d|", weekday];
format = [format stringByAppendingFormat:#"%d|", hour];
format = [format stringByAppendingFormat:#"%d|", minute];
format = [format stringByAppendingFormat:#"%d|", second];
format = [NSString stringWithFormat:#"%d|%d|%d|%d|%d|%d|%d", year, month, day, weekday, hour, minute, second];
}
result = format;
return result;
}
Example
NSDate * date = [self getDateWithMonth:12 day:24 year:1994];
NSString * dateInString = [self getStringFromDate:date dateType:DATE_TYPE_MMDDYYYY];
int month = [[[dateInString componentsSeparatedByString:#"|"] objectAtIndex:0] intValue];
int day = [[[dateInString componentsSeparatedByString:#"|"] objectAtIndex:1] intValue];
int year = [[[dateInString componentsSeparatedByString:#"|"] objectAtIndex:2] intValue];
NSLog(#"String of Date: \"%#\"", dateInString);
NSLog(#"Month: %d", month);
NSLog(#"Day: %d", day);
NSLog(#"Year: %d", year);
The method [self getDateWithMonth:12 day:24 year:1994] returns an NSDate object which is usually hard to read, so you can use [self getStringFromDate:date dateType:DATE_TYPE_MMDDYYYY] to get a string of an NSDate object.
Use the definitions (macros) to specify the format of the date you would like to get in the string.
For example:
DATE_TYPE_hhmmss would return the Hour|Minute|Second,
DATE_TYPE_MMDDYYYY would return the Month|Day|Year,
DATE_TYPE_MMDDYYYYhhmmss would return the Month|Day|Year|Hour|Minute|Second,
DATE_TYPE_MMDDYYYYWWhhmmss would return the Month|Day|Year|Weekday (#)|Hour|Minute|Second
and so on...
Console Log
2012-04-29 13:42:15.791 Atomic Class[1373:f803] String of Date: "12|24|1994"
2012-04-29 13:42:15.793 Atomic Class[1373:f803] Month: 12
2012-04-29 13:42:15.794 Atomic Class[1373:f803] Day: 24
2012-04-29 13:42:15.794 Atomic Class[1373:f803] Year: 1994