How to set Alarm Every Monday, Tuesday, Wednesday - iphone

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.

Related

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

Getting NSDate from a UIPickerView

I have a picker view similar to the alarm clock app on the iphone (first component = 1-12, second component = 0-60, third component = am/pm). What I do is this in the didSelect delegate of the picker view.
if (component == PICKER_HOURS) {
rowSelected = [self.hour objectAtIndex:row % 12];
self.hourSelected = rowSelected;
}
else if (component == PICKER_MINUTES) {
rowSelected = [self.minutes objectAtIndex:row % 60];
self.minuteSelected = rowSelected;
}
else {
rowSelected = [self.ampm objectAtIndex:row];
self.ampmSelected = rowSelected;
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter.dateFormat = #"h:mm a";
NSString *timeString = [NSString stringWithFormat:#"%#:%# %#", _hourSelected, _minuteSelected, _ampmSelected];
NSString *trimmedTimeString = [timeString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSDate *dateSelected = [dateFormatter dateFromString:timeString];
NSDate *dateForAlarm = [self alarmDateForDate:dateSelected];
------
- (NSDate *)alarmDateForDate:(NSDate *)dateSelected {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:[NSDate date]]; // set the date to the current date
NSDateComponents *timeComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:dateSelected]; // set the time to what's in the picker
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setYear:[dateComponents year]];
[dateComps setMonth:[dateComponents month]];
[dateComps setHour:[timeComponents hour]];
[dateComps setMinute:[timeComponents minute]];
NSDate *dateForAlarm = [calendar dateFromComponents:dateComps];
return dateForAlarm;
}
Is this the right approach? I realized that my dateFromString in the picker view is always the 1970 time. So I wasn't sure if this was 'standard' way to get the time from a picker view so that it is in the future to set a notification. Thanks!
Look at this -
Date Picker :-
m_pDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, 50, 50)];
m_pDatePicker.datePickerMode = UIDatePickerModeDate;
NSDate *minDate = [NSDate new];
[m_pDatePicker setMinimumDate:minDate];
m_pDatePicker.hidden = NO;
[m_pClientView addSubview:m_pDatePicker];
[m_pDatePicker addTarget:self action:#selector(pickDateLabel)forControlEvents:UIControlEventValueChanged];
NSDateComponents* comps = [m_pDatePicker.calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:m_pDatePicker.date];
int myDay = [comps day];
int myMonth = [comps month];
int myYear = [comps year];
pickDateLabel.text=[NSString stringWithFormat:#"%d/%d/%d",myMonth,myDay,myYear];
dueDateLabel.text=[NSString stringWithFormat:#"%d/%d/%d",myDay,myMonth,myYear];
[m_pDatePicker release];
[minDate release];
}
Picking Date -
- (void)pickDateLabel
{
NSDateComponents* comps = [m_pDatePicker.calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:m_pDatePicker.date];
int myDay = [comps day];
int myMonth = [comps month];
int myYear = [comps year];
pickDateLabel.text=[NSString stringWithFormat:#"%d/%d/%d",myMonth,myDay,myYear];
dueDateLabel.text=[NSString stringWithFormat:#"%d/%d/%d",myDay,myMonth,myYear];
}
Hope it helps !!

Issue with daily UILocaleNotification

I have created a notification system which push notification everyday at 12:02 AM but I don't know my code works and push notifications from app just for one or two days !! would you please help me to find the problem ?
- (void) LocalNotificationManager {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSPersianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit ) fromDate: now];
[componentsForFireDate year];
[componentsForFireDate month];
[componentsForFireDate day];
[componentsForFireDate setHour:00];
[componentsForFireDate setMinute:2];
[componentsForFireDate second];
NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForFireDate];
notification = [[UILocalNotification alloc]init];
notification.fireDate = fireDateOfNotification;
notification.timeZone = [NSTimeZone localTimeZone];
notification.repeatInterval= NSYearCalendarUnit;
NSString *date = [self showPersianFullDate];
notification.alertBody = [NSString stringWithFormat:#"today is : %# \n event : %# \n" ,date , events.text];
[self createEvents];
[self retriveData];
notification.alertAction = #"View";
notification.soundName = #"webcam_on.aif";
NSUserDefaults *notificationDefaults = [NSUserDefaults standardUserDefaults];
BOOL DAILYNOTIF = [notificationDefaults boolForKey:#"dn"];
if (DAILYNOTIF == YES) {
NSLog(#"DN is Active");
[[UIApplication sharedApplication] scheduleLocalNotification:notification];}
}
If you want to create a daily notification why have you set the interval to yearly?
Try changing this
notification.repeatInterval= NSYearCalendarUnit;
by
notification.repeatInterval= NSDayCalendarUnit;

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