How to add current Time(HH:MM:SS) to NSDate? - ios

I am using https://github.com/ruslanskorb/RSDayFlow to add calendar to my application.
I override the method as
// Prints out the selected date.
- (void)datePickerView:(RSDFDatePickerView *)view didSelectDate:(NSDate *)date {
self.transactionDate = date;
self.inputDateField.text = [[Helper getDateFormatterForClient] stringFromDate:self.transactionDate];
NSLog(#"transactionDate=%#", self.transactionDate);
[self.inputDateField resignFirstResponder];
}
All I want to add is current time HH:MM:SS to the date user selects.
I have no idea how to do this, any help is greatly appreciated
UPDATE
Currently, when the date is selected, I get
2015-01-15 10:34:35.210 myapp-ios[21476:60b] transactionDate=2015-01-15 08:00:00 +0000

If by "current time HH:MM:SS to the date" you mean that you want to replace the selected date's HH:MM:SS with the current HH:MM:SS, you can extract the relevant date components from the selected date, get the current datetime, extract the relevant time components, then add those components back into self.transactionDate, ex:
// Prints out the selected date.
- (void)datePickerView:(RSDFDatePickerView *)view didSelectDate:(NSDate *)date {
self.transactionDate = date;
self.inputDateField.text = [[Helper getDateFormatterForClient] stringFromDate:self.transactionDate];
NSLog(#"transactionDate=%#", self.transactionDate);
[self.inputDateField resignFirstResponder];
// Create an instance of the current calendar
NSCalendar *calendar = [NSCalendar currentCalendar];
// Break self.transactionDate into day, month, and year components
NSDateComponents* dateComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|
NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self.transactionDate];
// Save transaction date with just the day, month, and year
self.transactionDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
// Get the current datetime
NSDate *currentDate = [NSDate date];
// Extract the hour, minute, and second components
NSDateComponents *components = [calendar components:(NSCalendarUnitHour|
NSCalendarUnitMinute|NSCalendarUnitSecond) fromDate:currentDate];
// Add those hour, minute, and second components to
// self.transactionDate
self.transactionDate = [calendar dateByAddingComponents:components
toDate:self.transactionDate options:0];
}

This method Which I have created the in the category of `NSDate'.
+ (NSDate *)getDateWithCurrentTime:(NSDate *)date {
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components =
[gregorian components:(NSCalendarUnitDay |
NSCalendarUnitYear|NSCalendarUnitMonth) fromDate:date];
NSDateComponents *CurrentDateComponent =
[gregorian components:(NSCalendarUnitHour |
NSCalendarUnitMinute|NSCalendarUnitSecond) fromDate:[NSDate date]];
[components setHour:[CurrentDateComponent hour]];
[components setMinute:[CurrentDateComponent minute]];
[components setSecond:[CurrentDateComponent second]];
[components setTimeZone:[NSTimeZone systemTimeZone]];
return [gregorian dateFromComponents:components];
}

Related

How can I get First date and Last date of month in fscalender in ios?

How can I get month calendar start and end date?
From the screenshot, I need to get 1 aug 2017 and 31 aug 2017 in fscalender?
when i scroll then this method call but everytime get current date
- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar;
{
}
thanks!
You can use these two NSDate category methods for your need:
- (NSDate *)startDateOfMonth {
NSCalendar *current = [NSCalendar currentCalendar];
NSDate *startOfDay = [current startOfDayForDate:self];
NSDateComponents *components = [current components:(NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:startOfDay];
NSDate *startOfMonth = [current dateFromComponents:components];
return startOfMonth;
}
- (NSDate *)endDateOfMonth {
NSCalendar *current = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.month = 1;
components.day = -1;
NSDate *endOfMonth = [current dateByAddingComponents:components toDate:[self startDateOfMonth] options:NSCalendarSearchBackwards];
return endOfMonth;
}
You need to convert the date from your FSCalendar to NSDate:
- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar {
NSDate *date = ... //Conversion goes here
NSDate *startDateOfMonth = [date startDateOfMonth];
NSDate *endDateOfMonth = [date endDateOfMonth];
// convert back if you need to
}
The FSCalendar property currentPage returns the start date of currently showing page - this is the first day of the month or week depending on whether you are showing a month or week.
Then use NSCalendar methods to find the last day of the month or week that starts with currentPage. There are a number of ways to do this; e.g. add an NSDateComponents value or use one of the "next" methods such as nextDateAfterDate:matchingUnit:value:options:.
HTH
Get First date
- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar;
{
NSLog(#"did change to page %#",[self.dateFormatter stringFromDate:calendar.currentPage]);
}
-(void)calendarCurrentPageDidChange:(FSCalendar *)calendar{
[self.calendar selectDate:[self.calendar.currentPage fs_firstDayOfMonth]];
[self.calendar selectDate:[self.calendar.currentPage fs_lastDayOfMonth]];
}
You get First and Last date of Current Month by yourself. No need to get it from FSCalendar. For this see below code.
NDDate *currentDate = //Pass date which you get
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comp = [gregorian components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:currentDate];
[comp setMonth:[comp month]];
[comp setDay:1];
NSDate *firstDayDate = [gregorian dateFromComponents:comp];
[comp setMonth:[comp month]+1];
[comp setDay:0];
NSDate *lastDayDate = [gregorian dateFromComponents:comp];
NSLog(#"First : %#, Last : %#",firstDayDate,lastDayDate);
This way you are getting First and Last Date.

How to check whether a date belongs to this week or not in iOS?

Hello I have a date string like this.11/14/2016. What I want to do is check it whether is it
Today or This week or This month. I can compare today and the month. But how can I check whether this date belongs to "This Week"
Please help me.
Thanks
Given two dates,
NSDate *now = [NSDate date];
NSDate *then = // some other date
Find out if they're in the same week with:
BOOL sameWeek = [[NSCalendar currentCalendar] isDate:then equalToDate:now
toUnitGranularity:NSCalendarUnitWeekOfYear];
That line asks if they're "equal" with a granularity of a week, meaning that they're "equal" if they're in the same week.
Try below code,
- (void)thisWeek:(NSDate *)date
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todaysComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
NSUInteger todaysWeek = [todaysComponents weekOfYear];
NSDateComponents *otherComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:date];
NSUInteger datesWeek = [otherComponents weekOfYear];
//NSLog(#"Date %#",date);
if(todaysWeek==datesWeek){
NSLog(#"Date is in this week");
}else if(todaysWeek+1==datesWeek){
NSLog(#"Date is in next week");
}
}

Comparing two NSDate

I have a UIViewController with 2 buttons: today and yesterday. Every time the client clicked on today it needs to set the property _date for today and the same with yesterday.
The method which I set the property value is the following:
-(IBAction)dateButtonTouched:(id)sender
{
if(![sender isSelected])
{
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]];
[components setMinute:-[components minute]];
[components setSecond:-[components second]];
if([sender tag] == YESTERDAY)
{
[components setHour:-24];
_date= [cal dateByAddingComponents:components toDate: [NSDate date] options:0]; //YESTERDAY
}
else
{
NSDate *today = [NSDate date];
[components setHour:0];
_date= [cal dateByAddingComponents:components toDate: today options:0]; //TODAY
}
NSLog(#"user selected date %#",_date);
}
}
in the following method I'm trying to check if _date is today or yesterday:
-(void) viewWillLayoutSubviews
{
NSDateFormatter *dateFormat = [NSDateFormatter new];
[dateFormat setDateFormat:#"MM-dd-YY"];
self.dateLabel.text = [dateFormat stringFromDate:_date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]];
[components setMinute:-[components minute]];
[components setSecond:-[components second]];
[components setHour:0];
NSDate *today = [cal dateByAddingComponents:components toDate: [NSDate date] options:0]; //TODAY
[components setHour:-24];
NSDate *yesterday = [cal dateByAddingComponents:components toDate: [NSDate date] options:0]; //YESTERDAY
if([_date isEqualToDate:yesterday])
{
//do something
}
else if( [_date isEqualToDate:today])
{
//do something
}
}
The _date is never today or yesterday although if I debug it, print it or compare the description is the same.
An NSDate instance represents a specific moment in time. It is much more specific than "yesterday" or "today". Instead of trying to reset the hours, minutes, and seconds via date components, Maybe you should compare the components you're interested in: day, month, and year. Or you can use a calendar to compare at the component level:
NSDate *today = [NSDate date];
NSDate *someDay; // the date to compare
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *difference = [cal components:NSDayCalendarUnit fromDate:today toDate:someDay options:nil];
if (difference.day == -1) {
// yesterday
} else if (difference.day == 0) {
// today
}
Without knowing exactly what you want to do, it's harder to get more specific.
An NSDate object contains both date and time, encoded as a value that is essentially the number of microseconds since Jan 1 2000.
When you do two successive [NSDate date] operations you will get two different values, if not because the time has actually changed that much between the two then because most computer clock implementations assure that you get distinct values with each access.
NSDate's isEqualToDate function compares all of the bits of the two NSDate objects to see if they are exactly equal. This means that if the two are even a microsecond apart they will not appear to be equal.
If you want to see if two NSDate values are the same day you should either use NSDateFormatter to format them into strings and compare the strings, or use one of the NSDateComponent functions to calculate the number of days between them (several ways to do this).

Find all days of a week/month/year and add to NSMutableArray

I have an NSMutableArray, and i want to be able to pull out only the rows that are in a cetain time frame such as each week or month or year. I can get a date thats a week back so i would have the current date and the date a week back, but i need to be able to grab all those days then add them to an array so i can search through them.
This is how i am grabbing the day and the day a week back.
-(void)getCalDays {
cal = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];
NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)fromDate:date];
today = [cal dateFromComponents:comps];
NSLog(#"today is %#", today);
[self getWeek];
}
-(void)getWeek {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:-6];
weekDate = [cal dateByAddingComponents:components toDate:today options:0];
NSLog(#"Week of %# THRU %#", today, weekDate);
}
So how can i find all the days in between the two dates and load them into an array?
You're on your way. The key is to advance the component's day in a loop and extract a date from them.
NSMutableArray *result = [NSMutableArray array];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *startDate = // your input start date
NSDate *endDate = // your input end date
NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)fromDate:startDate];
NSDate *date = [cal dateFromComponents:comps];
while (![date isEqualToDate:endDate]) {
[result addObject:date];
[comps setDay:(comps.day + 1)];
date = [cal dateFromComponents:comps];
}
Note that this will result in a collection of dates inclusive of the first date, exclusive of the last date. You can probably work out on your own how to change the edge conditions.

Display NSDates in terms of week

Scenario:
I have an expense tracking iOS Application and I am storing expenses from a expense detail view controller into a table view (with fetched results controller) that shows the list of expenses along with the category and amount and date. I do have a date attribute in my entity "Money" which is a parent entity for either an expense or an income.
Question:
What I want is to basically categorize my expenses for a given week, a month, or year and display it as the section header title for example : (Oct 1- Oct 7, 2012) and it shows expenses amount and related stuff according to that particular week. Two buttons are provided in that view, if I would press the right button, it will increment the week by a week (Oct 1- Oct 7, 2012 now shows Oct8 - Oct 15, 2012) and similarly the left button would decrement the week by a week.
How would I accomplish that? I am trying the following code - doesn't work.
- (void)weekCalculation
{
NSDate *today = [NSDate date]; // present date (current date)
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:NSYearForWeekOfYearCalendarUnit |NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:today];
[comps setWeekday:1]; // 1: Sunday
firstDateOfTheWeek = [[calendar dateFromComponents:comps] retain];
[comps setWeekday:7]; // 7: Saturday
lastDateOfTheWeek = [[calendar dateFromComponents:comps] retain];
NSLog(#" first date of week =%#", firstDateOfTheWeek);
NSLog(#" last date of week =%#", lastDateOfTheWeek);
firstDateOfWeek = [dateFormatter stringFromDate:firstDateOfTheWeek];
lastDateOfWeek = [dateFormatter stringFromDate:lastDateOfTheWeek];
}
Code for incrementing date -
- (IBAction)showNextDates:(id)sender
{
int addDaysCount = 7;
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setDay:addDaysCount];
NSDate *newDate1 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:firstDateOfTheWeek options:0];
NSDate *newDate2 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:lastDateOfTheWeek options:0];
NSLog(#" new dates =%# %#", newDate1, newDate2);
}
Suppose the week shows like this (Nov4, 2012 - Nov10, 2012) and I press the increment button, I see in the console, date changes to Nov11,2012 and Nov.17, 2012 which is right but if I press the increment button again, it shows the same date again (Nov 11, 2012 and Nov.17, 2012).
Please help me out here.
Declare currentDate as an #property in your class. And try this.
#property(nonatomic, retain) NSDate *currentDate;
Initially set
self.currentDate = [NSDate date];
before calling this method.
- (void)weekCalculation
{
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:NSYearForWeekOfYearCalendarUnit |NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:self.currentDate];
[comps setWeekday:1]; // 1: Sunday
firstDateOfTheWeek = [[calendar dateFromComponents:comps] retain];
[comps setWeekday:7]; // 7: Saturday
lastDateOfTheWeek = [[calendar dateFromComponents:comps] retain];
NSLog(#" first date of week =%#", firstDateOfTheWeek);
NSLog(#" last date of week =%#", lastDateOfTheWeek);
firstDateOfWeek = [dateFormatter stringFromDate:firstDateOfTheWeek];
lastDateOfWeek = [dateFormatter stringFromDate:lastDateOfTheWeek];
}
Once the view is loaded self.currentDate value should be updated from showNextDates. Make sure it is not getting reset anywhere else.
- (IBAction)showNextDates:(id)sender
{
int addDaysCount = 7;
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setDay:addDaysCount];
NSDate *newDate1 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:firstDateOfTheWeek options:0];
NSDate *newDate2 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:lastDateOfTheWeek options:0];
NSLog(#" new dates =%# %#", newDate1, newDate2);
self.currentDate = newDate1;
}
I had needed similar thing in one of my old projects and achieved it via the code below. It sets this weeks date to an NSDate variable and adds/removes 7 days from day component in each button click. Here is the code:
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSDate *date = [NSDate date];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit|NSWeekdayCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date ];
//
[components setDay:([components day] - ([components weekday] )+2)];
self.currentDate = [calendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"dd.MM.yyyy HH:mm:ss";
self.datelabel.text = [formatter stringFromDate:self.currentDate];
The code above calculates this week start and sets it to currentDate variable. I Have two UIButtons with UIActions named prevClick and nextClick which calls the method that sets the next or previous weekstart:
- (IBAction)prevClick:(id)sender {
[self addRemoveWeek:NO];
}
-(void)addRemoveWeek:(BOOL)add{
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit|NSWeekdayCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self.currentDate ];
components.day = add?components.day+7:components.day-7;
self.currentDate = [calendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"dd.MM.yyyy HH:mm:ss";
self.datelabel.text = [formatter stringFromDate:self.currentDate];
}
- (IBAction)nextClk:(id)sender {
[self addRemoveWeek: YES];
}

Resources