i wan't to know exactly how many years it is between 2 NSDate's. (current Date and Date picker date)
i'm using NSTimeInterval (seconds) how to make it to years?
This code will make the value to Years:
NSTimeInterval distanceBetweenDates = [now timeIntervalSinceDate:date];
double secondsInAnYear = 31536000;
double YearsBetweenDates = distanceBetweenDates / secondsInAnYear;
NSString *dateString = [NSString stringWithFormat:#"%f", YearsBetweenDates];
labelView.text = dateString;
but i just get 6 decimals!
i want more than 6 decimals. How?
Take a look at -[NSCalendar (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts]. This does the calculation correctly. You can't assume a year always is exactly 31536000 seconds (leap year, or even those leap second(s) that get added occasionally).
Have you tried using %lf which is the designated specifier for long float/double values?
NSString *dateString = [NSString stringWithFormat:#"%lf", YearsBetweenDate];
Related
How can i store the calculated days between two dates in a variable so i can store the "days" in CloudKit
My code are (working to calculate days between dates):
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: datepicked, toDate: enddate, options: [])
print("DAYS LEFT :" , components)
Result are :
DAYS LEFT : <NSDateComponents: 0x7fd399ccb890>
Day: 1095
⌥-click on the variable components and then on NSDateComponents in the popup view.
In the documentation you can see that there is a property day to get the value of the .Day component.
var day: Int
So simply write
let day = components.day
I here have a piece of code which calculates the hours between two times in Objective-C. I'm sure you can rewrite this to make it days.
- (void)updateTimer {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
/* instead of conceptDate the date of the started and stopped time will be used when the database is edited so
date is nog a seperate column but is included in the colums start and stop to display working times that exceed
the 00.00 timestamp or take multiple days (for somewhat reason)*/
NSDate *date1 = [df dateFromString:[NSString stringWithFormat:#"%# %#", [self conceptDate], startedTime]];
NSDate *date2 = [df dateFromString:[NSString stringWithFormat:#"%# %#", [self conceptDate], [self getCurrentTime]]];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
if( interval < 0 ) {
interval = [date1 timeIntervalSinceDate:date2];
}
int hours = (int)interval / 3600; // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
int seconds = (interval - (hours*3600) - (minutes*60)); // interval minus hours part (in seconds) divided by 60 yields minutes
NSString *timeDiff = [NSString stringWithFormat:#"%02d:%02d:%02d", hours, minutes, seconds];
_workingTime.text = [NSString stringWithFormat:#"%#",timeDiff];
}
I hope this helps. Currently the time difference is stored in _workingTime object but can of course be stored in another string variable.
If you want to get days between two days then you should try this.
func daysFrom(FromDate:NSDate,ToDate:NSDate) -> Int{
return NSCalendar.currentCalendar().components(NSCalendarUnit.Calendar.exclusiveOr(NSCalendarUnit.Day), fromDate: date, toDate: ToDate, options: NSCalendarOptions.WrapComponents).day
}
Swift 4
func days(from:Date,to:Date) -> Int {
return Calendar.current.dateComponents([.day], from: from, to: to).day!
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
hours minutes seconds to seconds ios
I have a time formatted as such
// format: HH:mm:ss,AAA
// example for 2 hours, 35 minutes, 15 seconds, and 207 milliseconds
02:35:15,207
I'm trying to convert that into seconds as a double. The above example would turn into:
// 2 hrs * 3600 + 25 min * 60 + 15.207
9315.207
I figure I can pick apart each element with a scanner, but I'm thinking there's probably an easier way. I tried using NSDateFormatter but I need this as a double, not as an NSDate. Any suggestions? Thanks.
Further FYI
This is for use with the MPMoviePlayer and the currentTime property is a double. For any given section where I have data to show, I am checking if dataStartTime <= playerTime < dataEndTime. So I'm using double because that's the type for currentTime already.
Here is the solution, the idea is simple get two date one with your time and one with 00:00:00,000 time then take difference of their time.
- (double)secondsFromString:(NSString*)str {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss,SSS"];
NSString *dateString = #"1970-01-01";
NSDate *date = [formatter dateFromString:[NSString stringWithFormat:#"%# %#",dateString,str]];
NSDate *refDate = [formatter dateFromString:[NSString stringWithFormat:#"%# 00:00:00,000",dateString]];
double time = [date timeIntervalSince1970] - [refDate timeIntervalSince1970];
return time;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Create NSDate from Unix timestamp
I have an application where i am receiving date from json in unix timestamp format.This is the timestamp that i am receiving from json '1357178589630'.How to convert this timestamp into correct nsdate.I have used the following code for conversion but it is not working properly.This is my code:
double timestampval = [[updates objectForKey:#"timestamp"] doubleValue];
NSTimeInterval timestamp = (NSTimeInterval)timestampval;
NSDate *updatetimestamp = [NSDate dateWithTimeIntervalSince1970:timestamp];
When the timestamp is converted to nsdate using datewithtimeIntervalSince1970,in the updatetimestamp variable it displays '44977-04-11 12:40:30 +0000'
Try this one:
Might be you are getting timestamp is milli seconds instead of seconds, so you divide it by 1000.
EDIT Newer:
double timestampval = [[updates objectForKey:#"timestamp"] doubleValue]/1000;
NSTimeInterval timestamp = (NSTimeInterval)timestampval;
NSDate *updatetimestamp = [NSDate dateWithTimeIntervalSince1970:timestamp];
Previous :
double unixTimeStamp =1304245000;
NSTimeInterval timeInterval=unixTimeStamp/1000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setLocale:[NSLocale currentLocale]];
[dateformatter setDateFormat:#"dd-MM-yyyy"];
NSString *dateString=[dateformatter stringFromDate:date];
[NSDate dateWithTimeIntervalSince1970:timestamp] is correct. Seems that your timestamps is wrong.
Instead 1357178589630 it should be 1357178589.
Try here.
Update: as per Martin comment above.
Just divide the value by 1000.
try this code..
NSDate *dateTraded = [NSDate dateWithTimeIntervalSince1970 :[[updates objectForKey:#"timestamp"] integerValue]];
and Unix timestamps are in seconds, the value you have looks like a number of milliseconds since 1st January 1970. If you divide by 1000, you get 1264396813, which according to http://www.onlineconversion.com/unix_time.htm
I have tried so many things through the help I got, but I still can't figure out how to do it properly. Here's what I did lastly.
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:#"dd-MM-yyy"];
NSDate *currentDate = [NSDate date];
NSDate *fromDate = [NSString stringWithFormat:#"%#",[tempFormatter stringFromDate:currentDate]];
NSLog(#"currentDate %#", fromDate);
NSDate *toDate = [NSString stringWithFormat:#"%#",[tempFormatter stringFromDate:datePicker.date]];
NSLog(#"toDate %#", toDate);
NSTimeInterval interval = [toDate timeIntervalSinceDate:fromDate];
double leftDays = interval/86400;
NSLog(#"Total interval Between::%g",leftDays);
Tell me what I did wrong. Is it the NSDate conversion, that I am not doing properly ??
Thanks.
Your code is all messed up -- both toDate and fromDate are strings not NSDates. Your from date should just be currentDate, and your toDate should just be datePicker.date. You don't need to do anything with converting to strings or using a date formatter to get the time interval.
This line is creating problem.
NSDate *toDate = [NSString stringWithFormat:#"%#",[tempFormatter stringFromDate:datePicker.date]];
It changes the type of toDate from NSDate to __NSCFString. The NSTimeInterval take both of its arguments of NSDate type, but in your case only fromDate is NSDate type.
Change your code with these lines
NSDate *currentDate = [NSDate date];
NSDate *toDate = datePicker.date;
NSTimeInterval interval = [toDate timeIntervalSinceDate:currentDate];
It will surely work (inshaAllah).
You're certainly on the right track; however, you seem to be calling "timeIntervalSinceDate" using two NSString's (even though you're specifying fromDate and toDate as NSDates, look right after that- you're setting those two variables to NSString objects).
To get the interval you're looking for, try:
[datePicker.date timeIntervalSinceDate:currentDate];
That should get you the right interval. In addition, you may want to change leftDays to equal
double leftDays = abs(round(interval/86400));
This will stop leftDays from being an awkward number like -1.00005.
`Passing NSString to NSDate! this code is wrong
try
NSDate *curDate = [NSDate Date];
NSDate *pickerDate = datepicker.date;
then compare both these dates using NSTimeInterval
I initiated an NSDate with [NSDate date]; and I want to check whether or not it's been 5 hours since that NSDate variable. How would I go about doing that? What I have in my code is
requestTime = [[NSDate alloc] init];
requestTime = [NSDate date];
In a later method I want to check whether or not it's been 12 hours since requestTime. Please help! Thanks in advance.
NSInteger hours = [[[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:requestTime toDate:[NSDate date] options:0] hour];
if(hours >= 5)
// hooray!
int seconds = -(int)[requestTime timeIntervalSinceNow];
int hours = seconds/3600;
Basically here I'm asking how many seconds have passed since we first got our requestTime. Then with a little math magic, aka dividing by the number of seconds in an hour, we can get the number of hours that have passed.
A word of caution. Make sure you use the "retain" keyword when setting the requesttime. xcode likes to forget what NSDate objects are set to without it.
requestTime = [[NSDate date] retain];
Try using this method, or something along these lines.
- (int)hoursSinceDate :(NSDate *)date
{
#define NUBMER_OF_SECONDS_IN_ONE_HOUR 3600
NSDate *currentTime = [NSDate date];
double secondsSinceDate = [currentTime timeIntervalSinceDate:date];
return (int)secondsSinceDate / NUBMER_OF_SECONDS_IN_ONE_HOUR;
}
You can then do a simple check on the integer hour response.
int hours = [dateUtilityClass hoursSinceDate:dateInQuestion];
if(hours < 5){
# It has not yet been 5 hours.
}