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!
}
Related
I have NSString that has value "22/04/2013 05:56", as per the requirement I just want to calculate this time and date and show some condition based messages.
First condition:
If (String date = current date and stringtime = current time)||(string date = current date and string time < 1 minute from current time)
Second condition: If (String date = current date and stringtime > current time by how many minutes or hour)
Third Condition: To know is string date is yesterday.
Fourth Condition: To Know is string date is day before yesterday.
I am receiving this string from server. How can I achieve above things with this "22/04/2013 05:56" string.
You need to take 2 step:
convert string to NSDate
convert date to timeStamp
like below:
- (void) dateConverter{
NSString *string = #"22/04/2013 05:56";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:#"dd/MM/yyyy hh:mm"];
NSDate *date = [[NSDate alloc] init];
// voila!
date = [dateFormatter dateFromString:string];
NSLog(#"dateFromString = %#", date);
//date to timestamp
NSTimeInterval timeInterval = [date timeIntervalSince1970];
}
Then to achieve something like time ago following method will help, although it's not totally for you bu i believe you can modify it to help you!
- (NSString *) timeAgoFor : (NSDate *) date {
double ti = [date timeIntervalSinceDate:[NSDate date]];
ti = ti * -1;
if (ti < 86400) {//86400 = seconds in one day
return[NSString stringWithFormat:#"Today"];
} else if (ti < 86400 * 2) {
return[NSString stringWithFormat:#"Yesterday"];
}else if (ti < 86400 * 7) {
int diff = round(ti / 60 / 60 / 24);
return[NSString stringWithFormat:#"%d days ago", diff];
}else {
int diff = round(ti / (86400 * 7));
return[NSString stringWithFormat:#"%d wks ago", diff];
}
}
From string using dateformatter convert it to date.Then you have to compare the dates and get the value
NSString *str=#"22/04/2013 05:56";
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd/MM/YYYY hh:mm"];
NSDate *dateObj= [dateFormatter dateFromString:str];
NSLog(#"%#",dateObj);
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;
}
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];
I have a datepicker for the field "From" and "To" and I want the result of the subtraction.
for example: toValue-fromValue and the result would be in hours.
How to do that?
The difference of the two NSdate objects can be calculated using timeIntervalSinceDate:
NSTimeInterval diff = [toDate timeIntervalSinceDate:fromDate];
The result is given in seconds. Then, you calculate the hours like this:
NSInteger hours = diff / 3600;
If you have two NSDate objects you can compare them using the timeIntervalSinceDate method
NSDate* fromDate = //Get from date picker
NSDate* toDate = //Get from date picker
NSTimeInterval = [fromDate timeIntervalSinceDate:toDate];
NSInteger hours = timeInterval / 60*60; //60 seconds per minute, 60 minutes per hour
This is something I found myself spending hours to figure out and therefore want to share with you.
The question was: How do I determine the day of the year for a specific date?
e.g. January 15 is the 15th day and December 31 is the 365th day when it's not leap year.
Try this:
NSCalendar *gregorian =
[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger dayOfYear =
[gregorian ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSYearCalendarUnit forDate:[NSDate date]];
[gregorian release];
return dayOfYear;
where date is the date you want to determine the day of the year for. The documentation on the NSCalendar.ordinalityOfUnit method is here.
So the solution I came up with is pretty neat and simple and not in any way complicated.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"D"];
NSUInteger dayOfYear = [[formatter stringFromDate:[NSDate date]] intValue];
[formatter release];
return dayOfYear;
The trick here which I spent so long time to figure out was to use the NSDateFormatter. The "D" is the flag for day of year.
Hope that this was helpful to you who have the same problem as I had.
Using ARC and replacing deprecated symbols, John Feminella's answer would look like this:
NSCalendar *greg = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
NSUInteger dayOfYear= [greg ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitYear forDate:[NSDate date]];
Swift 4 variation:
let date = Date() // now
let calendar = Calendar(identifier: .gregorian)
let dayOfYear = calendar.ordinality(of: .day, in: .year, for: Date())
for Apple Swift version 5.4.2
let formatter = DateFormatter()
formatter.dateFormat = "d"
let day = formatter.string(from: Date())
if let dd = Int(day){
print("day: \(dd)")
}
With the NSDate class. Use message timeIntervalSinceDate. It will return you a NSTimeInterval value (actually it's a double) that represents the seconds elapsed since the date you want. After that, it's easy to convert seconds-to-days.
If you truncate seconds/86400 will give you days.
Let's say you want days since January 1st 2010.
// current date/time
NSDate *now = [[NSData alloc] init];
// seconds elapsed since January 1st 2010 00:00:00 (GMT -4) until now
NSInteval interval = [now timeIntervalSinceDate: [NSDate dateWithString:#"2010-01-01 00:00:00 -0400"]];
// days since January 1st 2010 00:00:00 (GMT -4) until now
int days = (int)interval/86400;