How to get the day component out of an NSDate? - iphone

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

Related

How to set Alarm Every Monday, Tuesday, Wednesday

i want set alarm every day please help me
i am so confused about it from many days.
i am using this code
-(void)localNotificationWithData:(NSDate *)firDate timeinterval:(int)interval{
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *pickerDate = firDate;
NSLog(#"%#",pickerDate);
NSDateComponents *dateComponents = [calender components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSWeekCalendarUnit)fromDate:pickerDate];
/*... here we get Weekdays throug loop....*/
int rand = arc4random()%100;
NSLog(#"%d",rand);
for (int i=0; i<[strMarkList length]; i++) {
NSString *getselectedCell=[strMarkList substringWithRange:(NSRange){i,1}];
NSLog(#"%i",[getselectedCell intValue]);
if ([getselectedCell intValue]== 0) {
[dateComponents setDay:1];
[dateComponents setWeekday:1];
NSDate *itemDate = [calender dateFromComponents:dateComponents];
[self repeatWeekDayInterval:itemDate rand:rand];
}else if ([getselectedCell intValue]== 1) {
[dateComponents setDay:2];
[dateComponents setWeekday:2];
NSDate *itemDate = [calender dateFromComponents:dateComponents];
[self repeatWeekDayInterval:itemDate rand:rand];
}else if ([getselectedCell intValue]== 2) {
[dateComponents setDay:3];
[dateComponents setWeekday:3];
localNofi.repeatInterval = kCFCalendarUnitWeekday+7;
NSDate *itemDate = [calender dateFromComponents:dateComponents];
[self repeatWeekDayInterval:itemDate rand:rand];
}else if ([getselectedCell intValue]== 3) {
[dateComponents setDay:4];
[dateComponents setWeekday:4];
NSDate *itemDate = [calender dateFromComponents:dateComponents];
[self repeatWeekDayInterval:itemDate rand:rand];
}else if ([getselectedCell intValue]== 4) {
[dateComponents setDay:5];
[dateComponents setWeekday:5];
NSDate *itemDate = [calender dateFromComponents:dateComponents];
[self repeatWeekDayInterval:itemDate rand:rand];
}else if ([getselectedCell intValue]== 5) {
[dateComponents setDay:6];
[dateComponents setWeekday:6];
NSDate *itemDate = [calender dateFromComponents:dateComponents];
[self repeatWeekDayInterval:itemDate rand:rand];
}else if ([getselectedCell intValue]== 6) {
[dateComponents setDay:7];
[dateComponents setWeekday:7];
NSDate *itemDate = [calender dateFromComponents:dateComponents];
[self repeatWeekDayInterval:itemDate rand:rand];
}
}
/*.....end.....*/
// NOW LOCALNOTIFICATION FIRE
}
-(void)repeatWeekDayInterval:(NSDate *)itemDate rand:(int)rand{
if (localNofi == nil)
return;
localNofi.fireDate = itemDate;
NSLog(#"%#",itemDate);
localNofi.timeZone = [NSTimeZone defaultTimeZone];
localNofi.alertBody = #"Time To Weak Up";
localNofi.alertAction = #"View";
localNofi.soundName = #"alarm-clock-bell.caf";
localNofi.applicationIconBadgeNumber = 1;
localNofi.repeatInterval = NSWeekCalendarUnit;
identifiLclNoti = rand;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:#"%d",identifiLclNoti] forKey:#"identifyKey"];
localNofi.userInfo = infoDict;
NSLog(#"%#",localNofi);
[[UIApplication sharedApplication] scheduleLocalNotification:localNofi];
}
please tell me what is wrong or i stuck in this problem for many day i search many time on google but can't find any good way please do something for me
please please help me......thanks
i just saw your schedule notification code, its fine and working. Just you need to change the below to pop up local notification every week.
localNofi.repeatInterval = NSWeekdayCalendarUnit;
I have tested it on iOS 6.0 simulator, got the required results, let me know if it didn't worked you.

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 do I get the countdown timer to show the countdown in days?

Trying to create a countdown Timer upto a certain date but I want it to show things in days and not Month, days (Like, 2Months 2Days) I would rather just have it show the actual number of days Like "62 Days" What should I change in the code? Thanks.
Here's the code I'm using for the CountDown.
#import "CountdownViewController.h"
#interface CountdownViewController ()
#end
#implementation CountdownViewController;
-(void)updateLabel;
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
char units = NSDayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:destinationDate options:0];
[dateLabel setText:[NSString stringWithFormat:#"%dDays", [components day]]];
}
- (void)viewDidLoad
{
[super viewDidLoad];
destinationDate = [NSDate dateWithTimeIntervalSince1970:1356393600];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateLabel) userInfo:nil repeats:YES];
// Do any additional setup after loading the view, typically from a nib.
}
The problem is that it is just showing me the days part. I played with the code to arrive to the code above but it used to be like this
-(void)updateLabel;
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
char units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:destinationDate options:0];
[dateLabel setText:[NSString stringWithFormat:#"%d %d %d %d %d", [components month], [components day], [components hour], [components minute], [components second]]];
}
Just copy the following two methods into your class, then call start the timer in viewDidLoad method. You need to change the desired date in getCountdownDate method:
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:#selector(getCountdownDate) userInfo:nil repeats: YES];
The methods are:
#pragma mark --
#pragma mark CountDownTimmer takes one date input
-(void)getCountdownDate
{
NSString *date = #"2013-09-09 20:30:00";
NSDate *toDate = [self formatADateFromString:date];
NSLog(#"Date: %#", toDate);
NSString *remainingCountDown = [self countDownTimerToSpecificDate:toDate];
NSLog(#"%#", remainingCountDown);
}
-(NSString *)countDownTimerToSpecificDate:(NSDate*)toDateParameter
{
NSDate *toDate = toDateParameter;
NSDate *currentDate = [NSDate date];
NSLog(#"To Date: %#, Current Date: %#", toDate, currentDate);
int units;
int months, days, hour, minit, second_t;
NSDateComponents *components;
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
units = NSDayCalendarUnit;
components = [calender components:units fromDate:currentDate toDate:toDate options:0];
days = [components day];
days = days%30;
units = NSMonthCalendarUnit;
components = [calender components:units fromDate:currentDate toDate:toDate options:0];
months = [components day];
months = months%12;
//int totalSec = [components second];
//int month = [components month];
units = NSHourCalendarUnit;
components = [calender components:units fromDate:currentDate toDate:toDate options:0];
hour = [components hour];
hour = hour%24;
units = NSMinuteCalendarUnit;
components = [calender components:units fromDate:currentDate toDate:toDate options:0];
minit = [components minute];
minit = minit%60;
units = NSSecondCalendarUnit;
components = [calender components:units fromDate:currentDate toDate:toDate options:0];
second_t = [components second];
second_t = second_t%60;
NSString *returnString = [NSString stringWithFormat:#"%d Months, %d Days, %d Hours, %d Minitues, %d Seconds",months, days, hour, minit, second_t];
//NSLog(#"%#", returnString);
return returnString;
}
try this method for get days from two date..
- (int)daysBetweenDates:(NSDate *)dt1:(NSDate *)dt2 {
int numDays;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:dt1 toDate:dt2 options:0];
numDays = [components day];
[gregorian release];
return numDays;
}
use this like bellow..
-(void)updateLabel;
{
int tempdays = [self daysBetweenDates:destinationDate :[NSDate date]];
[dateLabel setText:[NSString stringWithFormat:#"%dDays", tempdays]];
}
Before, supplying value to your label, in this case,dateLabel; you should concatenate your string comprising of years, months, days, or whatever it is...

Format date on iPhone returns (null)

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...

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)