I have two times let say 8.40am and 4.00pm,
What i want to do is, want to check whether current time falls between given time or not ?
I have tried this code snippet but it is not working :(
can you please help me out where i am making mistake ?
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currHr = [components hour];
NSInteger currtMin = [components minute];
NSString startTime = #"21:00";
NSString endTime = #"07:00";
NSArray *arr=[NSArray arrayWithObjects:startTime,endTime, nil];
int stHr = [[[[arr objectAtIndex:0] componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
int stMin = [[[[arr objectAtIndex:0] componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
int enHr = [[[[arr objectAtIndex:1] componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
int enMin = [[[[arr objectAtIndex:1] componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
int formStTime = (stHr*60)+stMin;
int formEnTime = (enHr*60)+enMin;
int nowTime = (currHr*60)+currtMin;
if(nowTime >= formStTime && nowTime <= formEnTime) {
NSLog(#"Btween......");
}
Thnaks in advance
EDIT:
NSDateComponents *openingTime = [[NSDateComponents alloc] init];
openingTime.hour = [timeA integerValue]; //8
openingTime.minute = [timeB integerValue]; //45
NSDateComponents *closingTime = [[NSDateComponents alloc] init];
closingTime.hour = [timeC integerValue]; //4
closingTime.minute = [timeD integerValue]; //43
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"hh:mm"];
NSString *nowTimeString = [formatter stringFromDate:[NSDate date]];
NSDate *now = [formatter dateFromString:nowTimeString]; //3:30
NSDateComponents *currentTime = [[NSCalendar currentCalendar] components:NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond
fromDate:now];
NSMutableArray *times = [#[openingTime, closingTime, currentTime] mutableCopy];
[times sortUsingComparator:^NSComparisonResult(NSDateComponents *t1, NSDateComponents *t2) {
if (t1.hour > t2.hour) {
return NSOrderedDescending;
}
if (t1.hour < t2.hour) {
return NSOrderedAscending;
}
// hour is the same
if (t1.minute > t2.minute) {
return NSOrderedDescending;
}
if (t1.minute < t2.minute) {
return NSOrderedAscending;
}
// hour and minute are the same
if (t1.second > t2.second) {
return NSOrderedDescending;
}
if (t1.second < t2.second) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
if ([times indexOfObject:currentTime] == 1) {
NSLog(#"We are Open!");
} else {
NSLog(#"Sorry, we are closed!");
}
create date components for opening and closing time.
create date components with hour, minute, second from date to check
place opening, closing and current time in an array
sort array. if current time is at index 1, it lies between opening and closing time
NSDateComponents *openingTime = [[NSDateComponents alloc] init];
openingTime.hour = 8;
openingTime.minute = 40;
NSDateComponents *closingTime = [[NSDateComponents alloc] init];
closingTime.hour = 16;
closingTime.minute = 0;
NSDate *now = [NSDate date];
NSDateComponents *currentTime = [[NSCalendar currentCalendar] components:NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond
fromDate:now];
NSMutableArray *times = [#[openingTime, closingTime, currentTime] mutableCopy];
[times sortUsingComparator:^NSComparisonResult(NSDateComponents *t1, NSDateComponents *t2) {
if (t1.hour > t2.hour) {
return NSOrderedDescending;
}
if (t1.hour < t2.hour) {
return NSOrderedAscending;
}
// hour is the same
if (t1.minute > t2.minute) {
return NSOrderedDescending;
}
if (t1.minute < t2.minute) {
return NSOrderedAscending;
}
// hour and minute are the same
if (t1.second > t2.second) {
return NSOrderedDescending;
}
if (t1.second < t2.second) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
if ([times indexOfObject:currentTime] == 1) {
NSLog(#"We are Open!");
} else {
NSLog(#"Sorry, we are closed!");
}
Try this -
NSString *startTimeString = #"08:00 AM";
NSString *endTimeString = #"06:00 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"hh:mm a"];
NSString *nowTimeString = [formatter stringFromDate:[NSDate date]];
int startTime = [self minutesSinceMidnight:[formatter dateFromString:startTimeString]];
int endTime = [self minutesSinceMidnight:[formatter dateFromString:endTimeString]];
int nowTime = [self minutesSinceMidnight:[formatter dateFromString:nowTimeString]];;
if (startTime <= nowTime && nowTime <= endTime)
{
NSLog(#"Time is between");
}
else {
NSLog(#"Time is not between");
}
-(int) minutesSinceMidnight:(NSDate *)date
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:date];
return 60 * (int)[components hour] + (int)[components minute];
}
Check the screenshot -
Related
Hello I had been working with Photos.framework but now I am stuck with predicate comparison of PHFetchOptions class in documents I see that we can use startDate to use in predicate. So my code is this
#interface ViewController ()
{
NSMutableArray * moments;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
moments = [NSMutableArray array];
if([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusNotDetermined)
{
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
[self loadCollections];
}];
}else
{
[self loadCollections];
}
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self loadCollections];
}
- (NSDate*)dateAddingDays:(NSInteger)days ToDate:(NSDate*)argDate
{
NSCalendar * gregorian = [NSCalendar currentCalendar];
NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"dd.MM.yyyy"];
NSString * dateString = [formatter stringFromDate:argDate];
NSDate * toWorkDate = [formatter dateFromString:dateString];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:days];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:toWorkDate options:0];
NSLog(#"%#",[formatter stringFromDate:date]);
return date;
}
- (void)loadCollections
{
PHFetchOptions * options = [[PHFetchOptions alloc]init];
options.predicate = [NSComparisonPredicate predicateWithFormat:#"startDate > CAST(%d,\"NSDate\")",[self dateAddingDays2:-1 ToDate:[NSDate date]].timeIntervalSince1970];
PHFetchResult * result = [PHAssetCollection fetchMomentsWithOptions:options];
if(result != nil)
{
NSLog(#"%i",result.count);
for (int i = 0; i < result.count; i++) {
NSLog(#"%#",[result objectAtIndex:i]);
[moments addObject:[result objectAtIndex:i]];
}
}
}
So my problem is this, I need fetch fotos from one day ago, I can make this work!! any help will be appreciated.
This is the answer, basically I replaced
- (NSDate*)dateAddingDays:(NSInteger)days ToDate:(NSDate*)argDate
{
NSCalendar * gregorian = [NSCalendar currentCalendar];
NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"dd.MM.yyyy"];
NSString * dateString = [formatter stringFromDate:argDate];
NSDate * toWorkDate = [formatter dateFromString:dateString];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:days];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:toWorkDate options:0];
NSLog(#"%#",[formatter stringFromDate:date]);
return date;
}
by
- (NSDate*)yesterday
{
NSCalendar * gregorian = [NSCalendar currentCalendar];
return [gregorian startOfDayForDate:[gregorian dateByAddingUnit:NSCalendarUnitDay value:-1 toDate:[NSDate date] options:NSCalendarWrapComponents]];
}
and also replace this
options.predicate = [NSComparisonPredicate predicateWithFormat:#"startDate > CAST(%d,\"NSDate\")",[self dateAddingDays2:-1 ToDate:[NSDate date]].timeIntervalSince1970];
by this
options.predicate = [NSComparisonPredicate predicateWithFormat:#"(startDate > %#)",[self yesterday]];
and now is working!!! thanks to #Larme
I am trying get hours and min in integer variable from string "5 hours 10 min".can anyone give me solution for this.
NSString *duration =#"5 hours 10 min";
int hours = 5
int min = 10
Please try following code for retrieve int value.
#try {
NSString *myString = #"5 hours 10 min";
NSArray *myWords = [myString componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#" "]
];
int hoursValue = 0, minuteValue = 0;
hoursValue = [[myWords objectAtIndex:0] intValue];
if([myWords count] > 2) {
minuteValue = [[myWords objectAtIndex:2] intValue];
}
NSLog(#"hours %d and Minute %d",hoursValue,minuteValue);
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
Use an NSDateFormatter to convert string1 into an NSDate, then get the required NSDateComponents:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"<Date format>"];
NSDate *date = [dateFormatter dateFromString:string1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
Learn more here
try this
#try
{
NSString *myString = #"5 hours 10 min";
NSArray *myWords = [myString componentsSeparatedByString:#" "];
int hoursValue = 0, minuteValue = 0;
if ([myWords count] == 4)
{
hoursValue = [[myWords objectAtIndex:0] intValue];
minuteValue = [[myWords objectAtIndex:2] intValue];
}
else if([myWords count] == 2)
{
if([[myWords objectAtIndex:1] isEqualToString:#"hours"] == yes)
{
hoursValue = [[myWords objectAtIndex:0] intValue];
}
else
{
minuteValue = [[myWords objectAtIndex:0] intValue];
}
}
NSLog(#"hours %d and Minute %d",hoursValue,minuteValue);
}
#catch(Exception *exception
{
}
Try this:
int hr,mins;
NSString *str=#"5 hours 10 min";
NSArray *firstWords = [str componentsSeparatedByString:#" "];
if (([[firstWords objectAtIndex:1] isEqualToString:#"hours"]||[[firstWords objectAtIndex:1] isEqualToString:#"hr"] ) &&([[firstWords objectAtIndex:3] isEqualToString:#"minutes"]||[[firstWords objectAtIndex:3] isEqualToString:#"min"])) {
hr=(int)[[firstWords objectAtIndex:0]integerValue];
mins=(int)[[firstWords objectAtIndex:2]integerValue];
if (mins > 60) {
hr+=mins/60;
mins =mins%60;
}
}
Try this
- (NSString *)timeFormatted:(int)totalSeconds
{
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return [NSString stringWithFormat:#"%02d:%02d:%02d",hours, minutes, seconds];
}
I am trying to detect is a specific date is within the last 7 days (within the last week).
I have found a method to do that, but its eating my performance in a tableview (chat controller).
The code is posted below, and i know it can be done a LOT better, but i am running out of ideas. Does somebody have better approach? thanks!
The code:
NSDate *date = [[_messages objectAtIndex:indexPath.row] date];
NSString *lastMessageDateString = [[[NVDate alloc] initUsingDate:date] stringValueWithFormat:#"dd/MM/yy"];
NSString *todayDateString = [[[NVDate alloc] initUsingToday] stringValueWithFormat:#"dd/MM/yy"];
NSString *yesterdayDateString = [[[[NVDate alloc] initUsingToday] previousDay] stringValueWithFormat:#"dd/MM/yy"];
NSString *earlier2DaysDateString = [[[[NVDate alloc] initUsingToday] previousDays:2] stringValueWithFormat:#"dd/MM/yy"];
NSString *earlier3DaysDateString = [[[[NVDate alloc] initUsingToday] previousDays:3] stringValueWithFormat:#"dd/MM/yy"];
NSString *earlier4DaysDateString = [[[[NVDate alloc] initUsingToday] previousDays:4] stringValueWithFormat:#"dd/MM/yy"];
NSString *earlier5DaysDateString = [[[[NVDate alloc] initUsingToday] previousDays:5] stringValueWithFormat:#"dd/MM/yy"];
NSString *earlier6DaysDateString = [[[[NVDate alloc] initUsingToday] previousDays:6] stringValueWithFormat:#"dd/MM/yy"];
NSString *earlier7DaysDateString = [[[[NVDate alloc] initUsingToday] previousDays:7] stringValueWithFormat:#"dd/MM/yy"];
//return the time of the message since it is today
if ([lastMessageDateString isEqualToString:todayDateString]) {
return [SAD.myE.timeFormat stringFromDate:date];
}
//return the string "yesterday" of the message since it is yesterday
else if ([lastMessageDateString isEqualToString:yesterdayDateString]) {
return #"Yesterday";
}
//return the string of the actual day of the message since it is within last 7 days
else if ([lastMessageDateString isEqualToString:earlier2DaysDateString] ||
[lastMessageDateString isEqualToString:earlier3DaysDateString] ||
[lastMessageDateString isEqualToString:earlier4DaysDateString] ||
[lastMessageDateString isEqualToString:earlier5DaysDateString] ||
[lastMessageDateString isEqualToString:earlier6DaysDateString] ||
[lastMessageDateString isEqualToString:earlier7DaysDateString]) {
return [SAD.myE.dayFormat stringFromDate:date];
}
//return the string date since the message is olf
else {
return [SAD.myE.dateFormat stringFromDate:date];
}
EDIT
Thanks to #vikingosegundo i have tried to use his solution to implement this solution. He since then made a category that made it even easier that i will try and implement now. Just for the curious ones:
- (NSString *)stringForDate:(NSDate *)date {
NSDate *now = [NSDate date]; // now
NSDate *today;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit // beginning of this day
startDate:&today // save it here
interval:NULL
forDate:now];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.day = 0;
NSDate * theDayToday = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:today options:0];
if ([date compare:theDayToday] == NSOrderedDescending) {
return #"today";
}
comp.day = -1;
NSDate * yesterday = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:today options:0];
if ([date compare:yesterday] == NSOrderedDescending) {
return #"yesterday";
}
comp.day = -7; // lets go 7 days back from today
NSDate * oneWeekBefore = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:today options:0];
if ([date compare:oneWeekBefore] == NSOrderedDescending) {
return #"within 7 days";
} else {
return #"before 7 days";
}
}
-(BOOL) dayOccuredDuringLast7Days
{
NSDate *now = [NSDate date]; // now
NSDate *today;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit // beginning of this day
startDate:&today // save it here
interval:NULL
forDate:now];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.day = -7; // lets go 7 days back from today
NSDate * oneWeekBefore = [[NSCalendar currentCalendar] dateByAddingComponents:comp
toDate:today
options:0];
if ([self compare: oneWeekBefore] == NSOrderedDescending) {
if ( [self compare:today] == NSOrderedAscending ) { // or now?
return YES;
}
}
return NO;
}
a complete command line example for last 7 days and yesterday. as category on NSDate
#import <Foundation/Foundation.h>
#interface NSDate (ExtendedComparions)
-(BOOL) dayOccuredDuringLast7Days;
-(BOOL) dayWasYesterday;
#end
#implementation NSDate (ExtendedComparions)
-(BOOL) _occuredDaysBeforeToday:(NSUInteger) nDaysBefore
{
NSDate *now = [NSDate date]; // now
NSDate *today;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit // beginning of this day
startDate:&today // save it here
interval:NULL
forDate:now];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.day = -nDaysBefore; // lets go N days back from today
NSDate * before = [[NSCalendar currentCalendar] dateByAddingComponents:comp
toDate:today
options:0];
if ([self compare: before] == NSOrderedDescending) {
if ( [self compare:today] == NSOrderedAscending ) {
return YES;
}
}
return NO;
}
-(BOOL) dayOccuredDuringLast7Days
{
return [self _occuredDaysBeforeToday:7];
}
-(BOOL) dayWasYesterday
{
return [self _occuredDaysBeforeToday:1];
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSDate *now =[NSDate date];
NSDate *twoDaysBefore = [[NSCalendar currentCalendar] dateByAddingComponents:(
{
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.day = -2;
comps;
})
toDate:now
options:0];
if ([twoDaysBefore dayOccuredDuringLast7Days]) {
NSLog(#"last week");
} else {
NSLog(#"not last week");
}
if ([twoDaysBefore dayWasYesterday]) {
NSLog(#"yesteday");
} else {
NSLog(#"not yesterday");
}
}
return 0;
}
I have a method that to create timestamp in long long integer format
EX: 1386752892
+ (NSNumber *)currentTimestampWithLongLongFormat
{
double timeStamp = ceil([[NSDate date] timeIntervalSince1970] * 1000);
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setGeneratesDecimalNumbers:false];
NSNumber *timeNumber = [NSNumber numberWithDouble:timeStamp];
NSString *timeString = [formatter stringFromNumber:timeNumber];
// NSTimeInterval is defined as double
return [NSNumber numberWithLongLong:[timeString longLongValue]];
}
But this will generate 13 digitals number
EX: 1386752811802
How to fix the problem and generate the correct format of number?
int timestamp = [[NSDate date] timeIntervalSince1970];
Try this
/**
* #param nil
* #return current time in mili second
*
* Fetch the current time stamp
*/
-(NSString *)currentTimeStamp {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithName:#"GMT"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp1 = [dateFormatter stringFromDate:[NSDate date]];
NSDate *curdate = [dateFormatter dateFromString:timeStamp1];
double unix_timestamp = [curdate timeIntervalSince1970];
NSString *timeStamp = [NSString stringWithFormat:#"%f",unix_timestamp*1000];
return timeStamp;
}
+ (NSString*) dateFromString:(NSString*)aStr
{
NSDateFormatter *formater = [[NSDateFormatter alloc] init];
[formater setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *date2 = [formater dateFromString:aStr];
[formater setDateFormat:#"d MMM,yyyy HH:mm"];
NSString *result = [formater stringFromDate:date2];
return result;
}
+ (NSString *)calculateTime:(NSString *)datetime :(NSString *)servertime
{
NSString *time;
NSDate *date1;
NSDate *date2;
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
date1 = [formatter dateFromString:datetime];
date2 = [formatter dateFromString:servertime];
}
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *differenceComponents = [calendar components:(NSDayCalendarUnit)
fromDate:date1
toDate:date2
options:0];
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];//[date1 timeIntervalSince1970] - [date2 timeIntervalSince1970];
int hour = interval / 3600;
int minute = (int)interval % 3600 / 60;
int seconds = (int)interval % 60;
hour=ABS(hour);
minute=ABS(minute);
seconds=ABS(seconds);
if ([differenceComponents day]>0) {
time= [NSString stringWithFormat:#"%ld %#", (long)[differenceComponents day],[NSString stringWithFormat:NSLocalizedString(#"daysago", nil)]];
}
else
{
if ([differenceComponents day] == 0) {
time= [NSString stringWithFormat:#"%ld %#", (long)[differenceComponents day],[NSString stringWithFormat:NSLocalizedString(#"dayago", nil)]];
if (hour>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(hour),[NSString stringWithFormat:NSLocalizedString(#"hourago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(hour),[NSString stringWithFormat:NSLocalizedString(#"hoursago", nil)]];
if (minute>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(minute),[NSString stringWithFormat:NSLocalizedString(#"minuteago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(minute),[NSString stringWithFormat:NSLocalizedString(#"minuteago", nil)]];
if (seconds>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(seconds),[NSString stringWithFormat:NSLocalizedString(#"secondago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(seconds),[NSString stringWithFormat:NSLocalizedString(#"secondsago", nil)]];
}
}
}
}
}
return time;
}
/// as per requirement we will use date formats
I have a UIDatePicker on one viewController that allows the user to set a calendar date, hour, and minute in the form of (sun July 22nd, 2:33pm) for a timer to be used in a separate viewController. On the separate viewController I am trying to have the timer displayed in an overlay on the UIImagePickerController in the form of 'dd:hh:mm:ss' left between the current NSDate (todays date/time) and the chosen datePicker date. Basically it's a countdown timer that starts counting down days, hours, minutes, seconds from the selected picker date, when the camera loads. My problem is that once the camera loads, the timer displays the correct remaining time in the correct format but then quickly disappears when it get's to my refreshLabel method. I Logged the values for my timerLabel and it is displaying correctly in the log but once the loop runs once it returns Null for everything. I had some help last night in determining that my problem could most likely be with the formatting of the date from string but I don't see what it is that could be wrong since the correct date is initially displayed when the camera first loads. So here's my code from my first viewController with the datePicker that sets the timerLabels time:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showDate"]) {
NSString *textFieldContents = self.textField.text;
NSString *counterContents = self.counter;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *deadline = [NSString stringWithFormat:#"%#/deadline.txt",
documentsDirectory];
NSString *flashName = [NSString stringWithFormat:#"%#/flashName.txt",
documentsDirectory];
NSError *fileError;
[textFieldContents writeToFile:flashName
atomically:YES
encoding:NSStringEncodingConversionAllowLossy
error:&fileError];
[counterContents writeToFile:deadline
atomically:YES
encoding:NSStringEncodingConversionAllowLossy
error:&fileError];
if(fileError.code == 0){
NSLog(#"deadline.txt was written successfully with these contents: %#,",
counterContents);
NSLog(#"flashName.txt was written successfully with these contents: %#,",
textFieldContents);}
else
[self performSegueWithIdentifier:#"showDate" sender:self];}
}
-(IBAction)refreshLabel; {
NSDate *selected = [NSDate dateWithTimeIntervalSince1970:[picker.date timeIntervalSince1970] - 1];
self.counter = [self.formatter stringFromDate:selected];
NSLog(#"selected is: %#", selected);
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComparisonComponents = [gregorian components:unitFlags fromDate:todaysDate toDate:selected options:NSWrapCalendarComponents];
NSInteger days = [dateComparisonComponents day];
NSInteger hours = [dateComparisonComponents hour];
NSInteger minutes = [dateComparisonComponents minute];
NSInteger seconds = [dateComparisonComponents second];
self.counter = [NSString stringWithFormat:#"%ld:%02ld:%02ld:%02ld", (long)days, (long)hours, (long)minutes, (long)seconds];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *deadline = [NSString stringWithFormat:#"%#/deadline.txt", documentsDirectory];
NSInteger success = [NSKeyedArchiver archiveRootObject:selected toFile:deadline];
NSLog(#"success is: %d",success);
}e *selected = [NSDate dateWithTimeIntervalSince1970:[[picker date] timeIntervalSince1970] - 1];
- (void)viewDidLoad
{ [super viewDidLoad];
self.textField.delegate = self;
self.formatter = [NSDateFormatter new];
[self.formatter setDateFormat:#"dd:hh:mm:ss"];
NSDate *now = [NSDate date];
picker.minimumDate = [NSDate date];
picker.maximumDate = [now dateByAddingTimeInterval:604800];
[picker setDate:now animated:YES];
self.counter = [now description];
self.now = [NSDate date];
self.counter = [self.formatter stringFromDate:self.now];}
And here's my viewController code for the UIImagePickerController that I need to have the timerLabel displayed and counting down correctly:
- (IBAction)startCamera:(id)sender {
if (self.image == nil && [self.videoFilePath length] == 0) {
self.imagePickerController = [[UIImagePickerController alloc] init];
self.imagePickerController.delegate = self;
self.imagePickerController.allowsEditing = NO;
self.imagePickerController.videoMaximumDuration = 10;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
}
else {
self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
self.imagePickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:self.imagePickerController.sourceType];
[self presentViewController:self.imagePickerController animated:NO completion:nil];}
[[NSBundle mainBundle] loadNibNamed:#"OverlayView" owner:self options:nil];
self.overlayView.frame = CGRectMake(160,8,0,0);
self.imagePickerController.cameraOverlayView = self.overlayView;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *deadline = [NSString stringWithFormat:#"%#/deadline.txt",
documentsDirectory];
NSString *flashName = [NSString stringWithFormat:#"%#/flashName.txt",
documentsDirectory];
NSError *fileError;
titleLabel.text = [NSString stringWithContentsOfFile:flashName
encoding:NSASCIIStringEncoding
error:&fileError];
timerLabel.text = [NSString stringWithContentsOfFile:deadline
encoding:NSASCIIStringEncoding
error:&fileError];
if(fileError.code == 0){
NSLog(#"deadline.txt was read successfully with these contents: %#,",
timerLabel.text);
NSLog(#"flashName.txt was read successfully with these contents: %#,",
titleLabel.text);}
self.startDate = [NSKeyedUnarchiver unarchiveObjectWithFile:deadline];
[self refreshLabel];
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(refreshLabel)
userInfo:nil
repeats:YES];
}
-(void)refreshLabel {
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComparisonComponents = [gregorian components:unitFlags fromDate:todaysDate toDate:self.startDate options:NSWrapCalendarComponents];
NSInteger days = [dateComparisonComponents day];
NSInteger hours = [dateComparisonComponents hour];
NSInteger minutes = [dateComparisonComponents minute];
NSInteger seconds = [dateComparisonComponents second];
self.timerLabel.text = [NSString stringWithFormat:#"%ld:%02ld:%02ld:%02ld", (long)days, (long)hours, (long)minutes, (long)seconds];
if (days == 0 && hours == 0 && minutes == 0 && seconds == 0) {
[self.timer invalidate];
NSLog(#"Time's up!");
}
}
As per our discussion last night, you can't use a date formatter this way, because you're looking at time in the future like 1 day 2 hours 5 minutes, not a date. One way to do this, would be to pass the picker's selected date to the image picker controller, and do pretty much the same thing you did in the first controller to get the date components. So in the first controller, save the picker date to the file rather than a string:
-(IBAction)refreshLabel; {
NSDate *selected = [NSDate dateWithTimeIntervalSince1970:[picker.date timeIntervalSince1970] - 1];
self.counter = [self.formatter stringFromDate:selected];
NSLog(#"selected is: %#", selected);
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit;
dateComparisonComponents = [gregorian components:unitFlags fromDate:todaysDate toDate:selected options:NSWrapCalendarComponents];
NSInteger days = [dateComparisonComponents day];
NSInteger hours = [dateComparisonComponents hour];
NSInteger minutes = [dateComparisonComponents minute];
NSInteger seconds = [dateComparisonComponents second];
self.counter = [NSString stringWithFormat:#"%ld:%02ld:%02ld:%02ld", (long)days, (long)hours, (long)minutes, (long)seconds];
self.textField.text = self.counter;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *deadline = [NSString stringWithFormat:#"%#/deadline.txt", documentsDirectory];
NSInteger success = [NSKeyedArchiver archiveRootObject:selected toFile:deadline];
NSLog(#"success is: %d",success);
}
Then in the image picker controller (I'm only showing the code needed for the timer label):
- (IBAction)startCamera:(id)sender {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *deadline = [NSString stringWithFormat:#"%#/deadline.txt", documentsDirectory];
NSError *fileError;
self.startDate = [NSKeyedUnarchiver unarchiveObjectWithFile:deadline];
[self refreshLabel];
if(fileError.code == 0){
NSLog(#"deadline.txt was read successfully with these contents: %#,", self.timerLabel.text);
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(refreshLabel) userInfo:nil repeats:YES];
}
}
-(void)refreshLabel{
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComparisonComponents = [gregorian components:unitFlags fromDate:todaysDate toDate:self.startDate options:NSWrapCalendarComponents];
NSInteger days = [dateComparisonComponents day];
NSInteger hours = [dateComparisonComponents hour];
NSInteger minutes = [dateComparisonComponents minute];
NSInteger seconds = [dateComparisonComponents second];
self.timerLabel.text = [NSString stringWithFormat:#"%ld:%02ld:%02ld:%02ld", (long)days, (long)hours, (long)minutes, (long)seconds];
if (days == 0 && hours == 0 && minutes == 0 && seconds == 0) {
[self.timer invalidate];
NSLog(#"Time's up!");
}
}