I have a method that updates a label and acts as a stop watch. It works fine accept when I format the string to factor days in it adds an additional day on. For example. If the stopwatch is started ten minutes ago the label will display:
01:00:10:00
it should just display 00:00:10:00
- (void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSDate *dateValue=[[NSUserDefaults standardUserDefaults] objectForKey:#"pickStart"];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:dateValue];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
// Create a date formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd:HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
// Format the elapsed time and set it to the label
NSString *timeString = [dateFormatter stringFromDate:timerDate];
self.stopWatchLabel.text = timeString;
}
Any help would be greatly appreciated.
What you are doing isn't appropriate. Your goal seems to be to convert timeInterval into days, hours, minutes, and seconds. Your use of timerDate and NSDateFormatter are not the proper way to achieve that goal.
timeInterval is not an offset from January 1, 1970 and timeInterval doesn't represent a date.
What you should do is get the difference between currentDate and dateValue as a set of NSDateComponents.
- (void)updateTimer {
NSDate *currentDate = [NSDate date];
NSDate *dateValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"pickStart"];
unsigned int unitFlags = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *comps = [[NSCalendar currentCalendar] components:unitFlags fromDate:dateValue toDate:currentDate options:0];
int days = [comps day];
int hours = [comps hours];
int minutes = [comps minutes];
int seconds = [comps seconds];
NSString *timeString = [NSString stringWithFormat:#"%d:%02d:%02d:%02d", days, hours, minutes, seconds];
self.stopWatchLabel.text = timeString;
}
There is no "additional day", the "date" you produce is a point in time after the 1st Jan 1970, so if your format includes the day you get at least a 1...
Just stick with the NSTimeInterval value and use NSDateComponentsFormatter - which also formats time intervals despite the name - or just do the math yourself to get the seconds, minutes, etc. and format those.
HTH
Related
I'm trying to create a method in Objective-C which would get the total number of minutes from a time value, written in "HHmm" format.
E.g. for "0210" the return value should be 130.
+ (int)totalMinutesFromHHmm:(NSString *)HHmm {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"HHmm"];
NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en-GB"];
[dateFormatter setLocale:enLocale];
NSDate *date = [dateFormatter dateFromString:HHmm];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:( NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
return (int)(hour * 60 + minute);
}
The problem is the hour component: it's always one hour off.
On this picture the NSDate shows a 09:22 time, but on the picture below you can see the hour component is 10 (the minute component is correctly set to 22).
I looked at other posts ('NSDateComponents on hour off', etc.), but couldn't find a solution that works. Any idea what I'm doing wrong?
Time Zone / locale might not need to come into this. I could be misunderstanding, but it seems like you are just trying to take a string in HHmm format and calculate the total minutes.
If you need to use NSDate still for some reason, this could work:
+ (int)totalMinutesFromHHmm:(NSString*)HHmm
{
NSString* refHHmm = #"0000";
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HHmm"];
NSDate* refDate = [dateFormatter dateFromString:refHHmm];
NSDate* date = [dateFormatter dateFromString:HHmm];
int minutes = [date timeIntervalSinceDate:refDate] / 60;
return minutes;
}
Otherwise, this could be a simpler option, since you know you will have a 4-character string representing the hours and minutes:
+ (int)totalMinutesFromHHmm:(NSString*)HHmm
{
int minutes = [[HHmm substringWithRange:NSMakeRange(0, 2)] intValue] * 60;
minutes += [[HHmm substringWithRange:NSMakeRange(2, 2)] intValue];
return minutes;
}
I am using UIDatePickerView in my project with timeInterval one minute. After selecting time if time is in hours then I have to do some stuff. So how can I detect if user selects time in hours or not?
Try this one , you can get hours between two date.
NSDate* date1 = someDate;
NSDate* date2 = someOtherDate;
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
Finally I got answer for my own question
NSDateFormatter *formatter23 = [[NSDateFormatter alloc]init];
[formatter23 setDateFormat:#"yyyy-MM-dd--HH:mm"];
NSDate* date1 = datePicker.date;
[formatter23 setDateFormat:#"mm"];
if ([[formatter23 stringFromDate:date1] isEqualToString:#"00"] || [[formatter23 stringFromDate:date1] isEqualToString:#"30"]){
NSLog(#"Date is in half an hour or hour");
} else{
NSLog(#"Some other");
}
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc]init]autorelease];
timeFormatter.dateFormat = #"HH";
NSString *date_Hour= [timeFormatter stringFromDate: localDate];
and simple way to get hour only use NSDateComponents class
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:[NSDate date]];
NSInteger hour= [components hour];
I am trying to get the days of a week in reference to their date.
Ex.: 14th October is a Wednesday.
I am creating a collection view cell and displaying the date as follows.
In the 14th cell it would display Wednesday, but how to get the next day as Thursday, then Friday...and so on.
I have got todays date and which day it is as follows,
day = [components day];
week = [components month];
year = [components year];
weekday = [components weekday];
NSString *string = [NSString stringWithFormat:#"%ld.%ld.%ld", (long)day, (long)week, (long)year];
NSLog(#"%#",string);
NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEEE"];
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in
NSLog(#"Today formatted date is %#",convertedDateString);
And i have found this method online, which returns the days in string when you pass the integer, but i am having trouble in this too, not understanding which integer to pass every time so I get different strings.
static inline NSString *stringFromWeekday(int weekday){
static NSString *strings[] = {
#"Sunday",
#"Monday",
#"Tuesday",
#"Wednesday",
#"Thursday",
#"Friday",
#"Saturday",
};
return strings[weekday];
}
You already got everything in place. You should be getting the correct day name in the convertedDateString string. You just have to add 24 hours to your todayDate object and use the dateformatter again to get the next day.
NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEEE"];
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in
You can get the next day like this.
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:(NSDayCalendarUnit | NSMonthCalenderUnit | NSYearCalenderUnit | NSWeekdayCalendarUnit) fromDate:today];
[dateComponents setDay:dateComponents.day+1];
NSDate *nextDay = [dateComponents date];
// Get the day by following same approach in the top
You will get days in a week from today using below code.
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
[gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];
iOS Programming: I just want to let iOS7 get the "America/Chicago" current date and time.
I searched a lot on Internet, but there are a lot of different solutions. I tried several solutions, but they do not work.
You can use the NSCalendar and NSTimezone classes. The following code segment demonstrates retrieving the current hour and minute. Extending it to retrieve other date components is straight-forward -
long hour;
long minute;
NSCalendar *cal=[NSCalendar currentCalendar];
NSDate *now=[NSDate date];
NSTimeZone *tz=[NSTimeZone timeZoneWithName:#"America/Chicago"];
[cal setTimeZone:tz];
NSDateComponents *comp=[cal components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:now];
hour=[comp hour];
min=[comp minute];
You can use this method,
- (NSDate *) getCountryDateWithTimeZone:(NSString *)zone
{
NSDate *now = [NSDate date];
NSTimeZone *szone = [NSTimeZone timeZoneWithName:zone];
NSInteger sourceGMTOffset = [szone secondsFromGMTForDate:now];
NSTimeInterval interval = sourceGMTOffset;
NSDate *destinationDate = [NSDate dateWithTimeInterval:interval sinceDate:now];
return destinationDate;
}
And,
[self getCountryDateWithTimeZone:#"America/Chicago"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *firstDate = #"2014-06-05 12:55:00";
NSDate *date=[dateFormatter dateFromString:firstDate];
NSDate *currentDate = [NSDate date];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:date toDate:currentDate options:0];
NSLog(#"The difference between from date and to date is %d days and %d hours and %d minute and %d second",components.day,components.hour,components.minute,components.second);
Output:
DateBookApp[1179:70b] The difference between from date and to date is 0 days and 22 hours and 57 minute and 12 Second
I have a date string that looks like this:
1391640679661
When I use this code:
NSString *seconds = #"1391640679661";
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[seconds doubleValue]];
I end up with this:
46069-05-03 07:27:41 +0000
So what's happening here? Is this a particular date format that I'm not accounting for? Or am I doing something else wrong?
Apple's own api will do all the hard work for you to format components as per your need.
If you want to get individual components as well you can apply below approach.
NSTimeInterval theTimeInterval = 1391640679661;
// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];
// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:date1 toDate:date2 options:0];
NSLog(#"Conversion: %dmin %dhours %ddays %dmoths",[conversionInfo minute], [conversionInfo hour], [conversionInfo day], [conversionInfo month]);
To convert a timestamp string into NSDate, you need to divid the timestamp double value to 1000, and then call dateWithTimeIntervalSince1970:
NSString *timestamp = #"1391640679661";
double seconds = [timestamp doubleValue]/1000.0;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
The result is:
2014-02-05 22:51:19 +0000