I am stuck a problem where i need to create a stepper by 7 day. I code for that but in case of last days of month it will remain continue with same month rather than it should be change in next month as well.
Same case needs to be implemented for the year.
For e.g if today is 30 dec 2016 then by adding 7 day it needs to be change as 7 jan 2017. Thanks in advance.
Try this. Here I have added 7 days from a particular date.
// Enter current date
NSString *currentDate = #"2016-12-30";
// Set number of days to add
int addDaysCount = 7;
// Set date formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
// Convert string to NSDate
NSDate *dateFromString = [dateFormatter dateFromString:currentDate];
// Initialize date component
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:addDaysCount];
// Retrieve date with increased days count
NSDate *newDate = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:dateFromString options:0];
NSLog(#"Current date: %#", [dateFormatter stringFromDate:dateFromString]);
NSLog(#"Updated date: %#", [dateFormatter stringFromDate:newDate]);
NSDate *now = [NSDate date];
NSDate *sevenDaysAgo = [now dateByAddingTimeInterval:+7*24*60*60];
Here add 7 days add to your current date
Related
I am trying to work with NSDate and it is not working for me, I am so confused right now. So the basic thing I want works, but it needs to be the day of today and not from the year 2000.
So what I want is that the Date should be the date of today with the hours that are in my string bU and eU and not the date from the year 2000 with the hours of my string.
Here is a piece of my code:
NSDate *localNotDate;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone localTimeZone]];
[df setDateFormat:#"HH:mm"];
NSDate *bU = [df dateFromString:[[[self alarmArray] objectAtIndex:arrayInt] beginUur]]; // This is a 24:00 format string
NSDate *eU = [df dateFromString:[[[self alarmArray] objectAtIndex:arrayInt] eindUur]]; // This is a 24:00 format string
if (intForInsideForLoop == 0) { // Setup NSDate on first loop.
localNotDate = bU; // This gives the date 2000-01-01 08:24
}
if (intForInsideForLoop < timesOnDay) {
localNotDate = [localNotDate dateByAddingTimeInterval:(interval * 60)]; // Adds minutes to the date of today.
NSDateFormatter *dtest = [[NSDateFormatter alloc] init];
[dtest setTimeZone:[NSTimeZone localTimeZone]];
[dtest setDateFormat:#"yyyy-MM-dd HH:mm"];
NSLog(#"%#", [dtest stringFromDate:localNotDate]); // This gives the date 2000-01-01 08:24. it should be like It's Today thursday so 2014-05-08 08:24
}
I have found the answer to my problem with the method Martin has given from the post. This method converts an "Time" string like (18:00) to the date of today at 18:00.
Here it is:
- (NSDate *)todaysDateFromString:(NSString *)time
{
// Split hour/minute into separate strings:
NSArray *array = [time componentsSeparatedByString:#":"];
// Get year/month/day from today:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
// Set hour/minute from the given input:
[comp setHour:[array[0] integerValue]];
[comp setMinute:[array[1] integerValue]];
return [cal dateFromComponents:comp];
}
This is how I setup my datePicker
self.datePicker = [[UIDatePicker alloc] init];
self.datePicker.timeZone = [NSTimeZone localTimeZone];
This is how I save the date that I selected
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
dateToSave = [formatter dateFromString:self.dateTextField.text];
NSLog(#"date saved = %#", dateToSave);
If I select Nov 18 2013 from the date picker, the NSLog shows
date saved = 2013-11-17 16:00:00 +0000
However, somewhere in my code, I need to get the difference in days between today's date and the date that I selected in the datepicker.
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:[NSDate date] toDate:dateSaved options:0];
NSLog(#"number of days => %i", [dateComponents day]);
Today is Nov 10. The date I saved is Nov 18. But the number of days difference is 7, instead of 8.
Your time zone is -8. 2013-11-17 16:00:00 +0000 equals to 2013-11-18 00:00:00 -0800.
Use [NSTimeZone timeZoneForSecondsFromGMT:0] instead of [NSTimeZone localTimeZone]
(This answer refers to the updated question about calculating the number of days
between two dates.)
The problem is that [NSDate date] is the current date+time, not the start of the current day. For example, if
[NSDate date] = "2013-11-10 10:00:00"
dateSaved = "2013-11-18 00:00:00" (both in your *local* timezone)
then the difference between
these two dates is "7 days and 14 hours". Therefore you get 7 as the number of days.
So you have to calculate the start of the current day first:
NSDate *startOfDay;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit
startDate:&startOfDay
interval:NULL
forDate:[NSDate date]];
and then use it in the calculation of the difference:
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit
fromDate:startOfDay
toDate:dateSaved
options:0];
NSDateFormatter *date_form=[[NSDateFormatter alloc]init];
[date_form setDateFormat:#"dd/MM/yyyy"];
NSDate *seletected_date = [datepicker date];
NSString *dateToSave=[[NSString alloc] initWithFormat:#"%#",[date_form stringFromDate:seletected_date]];
NSLog(#"date saved = %#", dateToSave);
Remove localtimezone
I am new to objective c. I wish to do the following:
Convert 24 hour format to 12 hour and then add +2 to hour and display it like: 4:00 pm
I get the 12 hour format but after adding +2 to it , the time is displayed always as "am", i.e even if it is 4 pm it is displayed as 4 am. Below is my code:
NSDate *now = [NSDate date];
NSDateFormatter *timeFormatter=[[NSDateFormatter alloc]init];
timeFormatter.dateFormat=#"hh:00 a";
NSString *currentHour=[timeFormatter stringFromDate:now ];
lblcurrentHour.text=[NSString stringWithFormat:#"%#",currentHour];
NSLog(#"%#",currentHour);
int hour=[[timeFormatter stringFromDate:now]intValue];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
dateFormatter1.dateFormat = #"HH:mm";
NSDate *date1 = [dateFormatter1 dateFromString:[NSString stringWithFormat:#"%02d:00",hour+=3]];
dateFormatter1.dateFormat = #"hh:mm a";
lblnextHour.text = [dateFormatter1 stringFromDate:date1]; // prints 4:00 am not pm
How do i solve this? Where am i getting wrong?
If I understand your requirements correctly, you want to take the current time and display the minutes as :00, anchoring to the current hour. Then you want to add two hours and display that time. The following code prints 04:00 AM and 06:00 AM to the console (local time is 0421.)
For calendrical calculations, I would avoid using NSDateFormatter as you are doing when you compute the time two hours from now. There are too many ways that can go astray. For example, what happens when the now time is 2300?
A good reference on calendrical calculations in Cocoa is here
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
// use gregorian calendar for calendrical calculations
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// get current date
NSDate *date = [NSDate date];
NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
units |= NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *currentComponents = [gregorian components:units fromDate:date];
// change the minutes to 0
currentComponents.minute = 0;
date = [gregorian dateFromComponents:currentComponents];
// format and display the time
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
timeFormatter.dateFormat = #"hh:mm a";
NSString *currentTimeString = [timeFormatter stringFromDate:date];
NSLog(#"Current hour = %#",currentTimeString);
// add two hours
NSDateComponents *incrementalComponents = [[NSDateComponents alloc] init];
incrementalComponents.hour = 2;
NSDate *twoHoursLater = [gregorian dateByAddingComponents:incrementalComponents toDate:date options:0];
// format and display new time
NSString *twoHoursLaterStr = [timeFormatter stringFromDate:twoHoursLater];
NSLog(#"Two hours later = %#",twoHoursLaterStr);
}
return 0;
}
Try this:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm:ss a"];
NSLog(#"Today's Date and Time: %#", [formatter stringFromDate:[NSDate date]]);
Output:
Today's Date and Time: 02:43:33 PM
I'm having a array of dates in this dd MMM yyyy format.Now I need to separate month and year in separate arrays from this array. Now if I select particular month and year say if I bind the year and month arrays in UIpickerview and select a particular year and month I need to get the corresponding list of dates in that year and month which was the dates in previous original array. For eg if Jan and 2012 are selected I need to get dates like {01 Jan 2012,05 Jan 2012,..28 Jan 2012} . I'm a beginner in objective C any help will be appreciated.
First convert your string to NSDate by using NSDateFormatter, then using comparator extract day,month and year from the date, change the date format to your required format.
Check the following.
NSString *date = #"10/12/2012";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:date];
NSCalendar *calendar =[NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit |NSYearCalendarUnit) fromDate:dateFromString];
int day =[components day]; //day from the date
int month = [components month];//month from the date
int year = [components year];// year from the date
[dateFormatter setDateFormat:#"dd MMM yyyy"] ;
NSString *InDate = [dateFormatter stringFromDate:dateFromString];//req format 10 jan 2012
Not exactly fulfilling your requirement but you can work around it.
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components =
[gregorian components:(NSMonthCalendarUnit |
NSYesrCalendarUnit) fromDate:today];
NSInteger month = [components month];
NSInteger year = [components year];
We are building an app which requires the storage of a date for an entry on the device, the app will be international so we hit two dilema's / challenges.
User Preferences
If the user chooses the 12 hour rahter than 24 hour format we are returned from [NSDate date] a date like this 2012-07-17 11:26:03 AM which for sorting in a SQLite database is less than optimal as we cannot store it as a date.
User Locale
Typically this is ok however here in blighty we have a wonderfult thing called british summertime. which adds one hour every October 25th - 30th in a cycle and removes one hour every March 25 - 31th in a cycle so if no adjustment is made for 8 months of the year the time is one hour behind.
What I need to achieve is a consistent date formatted like this: 2012-07-17 11:26:03 no matter where the device is located and also taking into account where GMT+1 comes into place.
Any help would be awesome.
EDIT*
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm";
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT+01:00"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
NSDate *localDate = [dateFormatter dateFromString:timeStamp];
NSLocale* currentLocale = [NSLocale currentLocale];
NSString* countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
NSLog(#"Country Code: %#", countryCode);
NSLog(#"Current Loacle: %#", currentLocale);
if(([countryCode isEqualToString: #"GB"])){
NSDate *mydate = [NSDate date];
NSDate *fiddlyFoo = [mydate dateByAddingTimeInterval:3600];
NSLog(#"Print GMT +1 %#",fiddlyFoo);
} else {
NSLog(#"Print GMT Local %#",localDate);
}
I'm doing something like this now. Note that NSDate "knows" about the current timezone and daylight savings time etc. So you just need to get the GMT version of the time in a sortable representation. I'd suggest RFC 3339 but you can use variations on it per your needs:
This code:
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
// Create a local date for London, for testing purposes
NSDateComponents *comps = [NSDateComponents new];
[comps setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/London"]];
[comps setDay:1];
[comps setMonth:7];
[comps setYear:2012];
[comps setHour:14];
NSDate *date = [gregorian dateFromComponents:comps];
// Just want to show this date is 2PM in London July 1st
NSDateFormatter *curFormat = [NSDateFormatter new];
[curFormat setDateStyle:NSDateFormatterFullStyle];
[curFormat setTimeStyle:NSDateFormatterFullStyle];
NSLog(#"Reference date is good no: %#", [curFormat stringFromDate:date]);
// So now we get the date as a rfc3339 string, referenced to GMT
NSString *timeString;
{
NSDateFormatter *rfc3339 = [NSDateFormatter new];
[rfc3339 setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
rfc3339.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
timeString = [rfc3339 stringFromDate:date];
}
// referenced to UTC (sortable with any other time), can save in SQL DB etc
NSLog(#"Date as rfc3339 string: %#", timeString);
// Now lets convert it back into a BST time
NSDate *newDate;
{
NSDateFormatter *rfc3339 = [NSDateFormatter new];
[rfc3339 setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
rfc3339.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
newDate = [rfc3339 dateFromString:timeString];
// we want to show this as a string 2012-07-17 11:26:03
NSDateFormatter *newFormatter = [NSDateFormatter new];
[newFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"]; // local time
[newFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/London"]];
NSLog(#"Local string using 24 hour clock: %#", [newFormatter stringFromDate:newDate]);
}
Generates this output, which I believe is what you want:
TimeTester[58558:f803] Reference date is good no: Sunday, July 1, 2012 9:00:00 AM Eastern Daylight Time
TimeTester[58558:f803] Date as rfc3339 string: 2012-07-01T13:00:00Z
TimeTester[58558:f803] Local string using 24 hour clock: 2012-07-01 14:00:00