display last 5days date in ios - ios

I am trying to display last 5 days date. But it display only last date(yesterday). I am using the following code to display it.
.h file:
NSInteger getDist;
NSString *lastdate;
NSDateFormatter *dateFormatter;
NSDate *sevenDaysAgo;
NSDate *dateAfterDecrement;
NSString *dateString;
int i;
viewDidLoad:
NSDate *currDate = [NSDate date];
dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd.MM.YY"];
dateString = [dateFormatter stringFromDate:currDate];
_currentDate.text=dateString;
-(void)display
{
for(i=1;i<=5;i++)
{
lastdate = _currentDate.text;
[dateFormatter setDateFormat:#"dd.MM.YY"];
sevenDaysAgo = [dateFormatter dateFromString:lastdate];
dateAfterDecrement=[sevenDaysAgo initWithTimeIntervalSinceNow:-
(24*60*60)];
}
_currentDate.text = [dateFormatter stringFromDate:dateAfterDecrement];
}
Please suggest me.

Here's how to display today's date, then the last 4 days' dates.
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM dd, yyyy"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
int DAY_TO_SECONDS = -60*60*24;
for (int n=0; n<5; n++)
{
NSDate* date = [[NSDate date] dateByAddingTimeInterval:DAY_TO_SECONDS*n];
NSString* dateString = [formatter stringFromDate:date];
NSLog(#"%#", dateString);
}
This produces output like:
2015-02-23 13:18:30.657 ClientInfo[1418:557691] Feb 23, 2015
2015-02-23 13:18:30.658 ClientInfo[1418:557691] Feb 22, 2015
2015-02-23 13:18:30.658 ClientInfo[1418:557691] Feb 21, 2015
2015-02-23 13:18:30.658 ClientInfo[1418:557691] Feb 20, 2015
2015-02-23 13:18:30.658 ClientInfo[1418:557691] Feb 19, 2015

you can decrement current date to this way by the number of days you want to get
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *datecomponents = [calendar components:NSYearCalendarUnit
| NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:[NSDate date]];
for (int i = 0; i < 5; ++i) {
NSDate *date = [calendar dateFromComponents:datecomponents];
NSLog(#"%#",date);
--datecomponents.day;
}

Related

a date string without year to NSDate with year

I have a date string of
"5:09 pm Wed Sep 2",which is coming from server.
when converting the string into NSDate.
"2000-09-02 17:09:00 +0000" but the year should have been "2015" like:
"2015-09-02 17:09:00 +0000"
Here is my code please let me know where is the problem
NSString *dateStr = #"5:09 pm Wed Sep 2";
// Convert string to date object
NSString *dateFormat= ([self hasAMPM])?#"hh:mm a EEEE MMM d":#"hh:mm a EEEE MMM d" ;
NSDate * date = [self toLocalTime:[self convertDateFromString:dateStr OutputFormat:dateFormat]];
///****
-(BOOL)hasAMPM{
NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:#"j" options:0 locale:[NSLocale currentLocale]];
NSRange containsA = [formatStringForHours rangeOfString:#"a"];
BOOL hasAMPM = containsA.location != NSNotFound;
return hasAMPM;
}
-(NSDate *)toLocalTime:(NSDate *)date
{
NSTimeZone *tz = [NSTimeZone systemTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: date];
return [NSDate dateWithTimeInterval: seconds sinceDate: date];
}
-(NSDate *)convertDateFromString:(NSString *)strDate OutputFormat:(NSString *)outPutFormat
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:outPutFormat];
NSDate *date1= [formatter dateFromString:strDate];
return date1;
}
Please help me to get out of this situation.
If you want to add the year in your date according to current date, this works for dates from 1970 onwards, haven't checked for beyond that:
NSString *dateStr = #"5:09 pm Wed Sep 2";
NSString *dateString = [dateStr stringByAppendingString:#" 1970"];
// Convert string to date object
NSString *dateFormat= ([self hasAMPM])?#"hh:mm a EE MMM d yyyy":#"hh:mm a EE MMM d yyyy" ;
NSDate * date = [self toLocalTime:[self convertDateFromString:dateString OutputFormat:dateFormat]];
NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
greCalendar.timeZone = [NSTimeZone systemTimeZone];
NSDateComponents *componenetsForCurrent = [greCalendar componentsInTimeZone:[NSTimeZone systemTimeZone] fromDate:[NSDate date]];
NSInteger year = componenetsForCurrent.year;
NSDate *requiredDate = [greCalendar dateByAddingUnit:NSCalendarUnitYear value:(year-1970) toDate:date options:NSCalendarWrapComponents];
You can split your date using NSDateComponents, and work with year independently
NSDateComponents *dateComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
[dateComponents setYear:someYear];
date = [calendar dateFromComponents:dateComponents];

Adding an amount of hours to NSDate isn't working?

I've spent a good few hours trying to make this work. Here's what I'm trying to do:
Take input from a UITextField in the form HH:mm AM/PM
Convert that string into an NSDate object, and update the month/day/year properties of that NSDate to reflect the curren month/day/year.
Add 4 hours to the time of the NSDate object.
That last bit isn't working. It works for times such as 12:00 PM and 12:30 PM but for times such as 2:30 PM, it will output 4:30 PM rather than 6:30 PM as expected. Here is my code, broken up to reflect those three tasks.
Task 1 - checking to see if the text input was HH:mm AM/PM
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
[format setTimeZone:[NSTimeZone systemTimeZone]];
[format setDateFormat:#"HH:mm a"];
NSString *dateString = textField.text;
NSLog(#"input datestring: %#", dateString);
NSDate *parsed = [format dateFromString:dateString];
if (parsed) {
NSLog(#"datestring is valid, %#", parsed);
}
Task 2- Updating the m/d/y components of that date to reflect today's.
//gregorian calendar, get the hour and minute components from the input time
NSCalendar *greg = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [greg components: NSCalendarUnitHour | NSCalendarUnitMinute fromDate:parsed];
//get the month/day/year components from the current date
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
//set the components of the original date to the month/day/year components of today
[components setYear:comps.year];
[components setDay:comps.day];
[components setMonth:comps.month];
//create the new date.
NSDate* newDate = [greg dateFromComponents:components];
NSLog(#"########### %#", newDate);
Task 3 - Add 4 hours.
int hours = 4 ;
NSString *output;
NSDateComponents *add = [[NSDateComponents alloc] init];
[add setHour:hours];
newDate = [greg dateByAddingComponents:add toDate:newDate options:0];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterShortStyle];
[df setTimeStyle:NSDateFormatterShortStyle];
output = [df stringFromDate:newDate];
NSLog(#"new date: %#", output);
Log:
2015-08-27 16:03:35.672 Del Taco[1960:117431] input datestring: 2:30 pm
2015-08-27 16:03:35.673 Del Taco[1960:117431] datestring is valid, 2000-01-01 20:30:00 +0000
2015-08-27 16:03:35.673 Del Taco[1960:117431] ########### 2015-08-27 19:30:00 +0000
2015-08-27 16:03:35.674 Del Taco[1960:117431] new date: 8/27/15, 4:30 PM
I think I have this figured out. It was my date formatter where I set the format like this:
#"HH:mm a"
I went to Unicode's website to double check that I was doing this right, and ended up changing my format string to:
#"h:mm a"
And things seem to be working out well!

NSDate: Extract Date ONLY

I'm using the code below to extract the date only from NSDate. What am I doing wrong?
NSDate* now = [NSDate date];
NSLog(#"Now Date %#",now);
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat = #"dd-MM-yyyy";
NSString *stringDate = [format stringFromDate:now];
NSDate *todaysDate = [format dateFromString:stringDate];
NSLog(#"Today's Date without Time %#", todaysDate);
Log:
2014-06-21 12:27:23.284 App[69727:f03] Now Date 2014-06-21 19:27:23 +0000
2014-06-21 12:27:23.285 App[69727:f03] Today's Date without Time 2014-06-21 07:00:00 +0000
Why am I getting: 07:00:00 +0000 at the end?
I would like to get an NSDate in the in the following format:
2014-06-21 00:00:00 +0000
Having 0's for time, seconds, etc. is not important.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
should work
Another solution: using NSCalendar:
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:1]]; // I'm in Paris (+1)
NSDateComponents *comps = [cal components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
comps.hour = 0;
comps.minute = 0;
comps.second = 0;
NSDate *newDate = [cal dateFromComponents:comps ];
NSLog(#"date: %#",newDate);
Adjust timezone param, you will receive something like: date: 2014-06-21 00:00:00 +0000
If you don't care about the time, NSDate is not the right storage structure for you. An NSDate represents a specific moment in time - there is no NSDate without a time. What you're seeing is the logged description of an NSDate, which is the full printout in GMT.
If you want to keep track of the year, month and day only, then use NSDateComponents instead, and extract only the components you are interested in. You can then use the components object and pass it around as you like.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
With the code above, the NSDate object will HAVE time. But the string will be a date only text.
This is the code using .
#include <time.h>
- (NSDate *)dateFromISO8601String:(NSString *)string {
if (!string) {
return nil;
}
struct tm tm;
time_t t;
strptime([string cStringUsingEncoding:NSUTF8StringEncoding], "%Y-%m-%dT%H:%M:%S%z", &tm);
tm.tm_hour = 0;
tm.tm_min = 0;
tm.tm_sec = 0;
tm.tm_isdst = -1;
t = mktime(&tm);
return [NSDate dateWithTimeIntervalSince1970:t + [[NSTimeZone localTimeZone] secondsFromGMT]];
}
- (NSString *)ISO8601String:(NSDate*)aDate {
struct tm *timeinfo;
char buffer[80];
time_t rawtime = [aDate timeIntervalSince1970] - [[NSTimeZone localTimeZone] secondsFromGMT];
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%dT%H:%M:%S%z", timeinfo);
return [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
}
NSString *currentDateStr = [self ISO8601String:[NSDate date]];
NSDate *dateWithoutTime = [self dateFromISO8601String:currentDateStr];
NSLog(#"currentDateStr: %#",currentDateStr);
NSLog(#"dateWithoutTime: %#",dateWithoutTime);

Add 3 Hours to an NSDate's Hour

I want to add 3 hours to my current date. I am using the following code to add hours but it adds 6 hours to the current date.
NSDate *n = [NSDate date];
int daysToAdd = 3; // or 60 :-)
// set up date components
NSDateComponents *components1 = [[[NSDateComponents alloc] init] autorelease];
[components1 setHour:daysToAdd];
// create a calendar
NSCalendar *gregorian12 = [NSCalendar currentCalendar];
NSDate *newDate2 = [gregorian12 dateByAddingComponents:components toDate:n options:0];
NSLog(#"Clean: %#", newDate2);
Result is :-
2013-09-10 12:25:24.752 project[1554:c07] Clean: 2013-09-10 06:55:15 +0000
Try this
NSString *strCurrentDate;
NSString *strNewDate;
NSDate *date = [NSDate date];
NSDateFormatter *df =[[NSDateFormatter alloc]init];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strCurrentDate = [df stringFromDate:date];
NSLog(#"Current Date and Time: %#",strCurrentDate);
int hoursToAdd = 3;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:hoursToAdd];
NSDate *newDate= [calendar dateByAddingComponents:components toDate:date options:0];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strNewDate = [df stringFromDate:newDate];
NSLog(#"New Date and Time: %#",strNewDate);
Output
Current Date and Time: Sep 10, 2013, 1:15:41 PM
New Date and Time: Sep 10, 2013, 4:15:41 PM
NSDate *CurrentTimedate = [NSDate date];
NSLog(#"%#",CurrentTimedate);
NSDate *newDate = [CurrentTimedate dateByAddingTimeInterval:60*60*3];
NSLog(#"%#",newDate);
NSDate *newDate = [oldDate dateByAddingTimeInterval:hrs*60*60];

different date range for ios versions

when calling method for simulator
version 6.1 it shows:
year---2012
week no---52
weekday---2
resultdate---2012-12-16 18:30:00 +0000
date time is 17 Dec 2012 To 23 Dec 2012
version 5.0 it shows:
year---2012
week no---52
weekday---2
resultdate---2012-12-23 18:30:00 +0000
date time is 24 dec. 2012 To 30 dec. 2012
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
gregorian.Locale = [NSLocale currentLocale];
//[gregorian setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
gregorian.firstWeekday = 2; // Sunday = 1, Saturday = 7
NSDateComponents *components = [gregorian components:NSYearForWeekOfYearCalendarUnit |NSWeekOfYearCalendarUnit |NSWeekdayOrdinalCalendarUnit fromDate:[NSDate date]];
[components setYearForWeekOfYear:2012];
[components setWeekOfYear:52];
[components setWeekdayOrdinal:2];
NSLog(#"year---%ld",(long)[components yearForWeekOfYear]);
NSLog(#"week no---%ld",(long)[components weekOfYear]);
NSLog(#"weekday---%ld",(long)[components weekdayOrdinal]);
NSDate *resultDate = [gregorian dateFromComponents:components];
NSLog(#"resultdate---%#",resultDate);
NSDate *startOfTheWeek;
NSDate *endOfWeek;
NSTimeInterval interval;
[gregorian rangeOfUnit:NSWeekOfYearCalendarUnit startDate:&startOfTheWeek interval:&interval forDate:resultDate];
endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval-1];
and to get the out put dateformatter used is
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd MMM yyyy"];
NSString *str_StartOfTheWeek = [dateFormatter stringFromDate:startOfTheWeek];
NSString *str_EndOfWeek = [dateFormatter stringFromDate:endOfWeek];
NSLog(#"date time is %#",[NSString stringWithFormat:#"%# To %#",str_StartOfTheWeek,str_EndOfWeek]);
return [NSString stringWithFormat:#"%# To %#",str_StartOfTheWeek,str_EndOfWeek];
how to solve this issue pls help.
To set a weekday (e.g. 2 = Monday) you have to use the NSWeekdayCalendarUnit and setWeekday:, not NSWeekdayOrdinalCalendarUnit and setWeekdayOrdinal::
NSDateComponents *components = [gregorian components:NSYearForWeekOfYearCalendarUnit|NSWeekOfYearCalendarUnit|NSWeekdayCalendarUnit
fromDate:[NSDate date]];
[components setYearForWeekOfYear:2012];
[components setWeekOfYear:52];
[components setWeekday:2];
With this modification, the output is
date time is 17 Dec 2012 To 23 Dec 2012
on both iOS 5 and iOS 6.

Resources