I am creating a calendar based app.
I have two dates say present date, and future date(due date), now i need to show the difference between these two dates in terms of days, hours, minutes & seconds and i want to show a timer which will continues to decrement second by second as the time increases and ultimately reaches to zero when due date comes.Basically it will be showing that how much days, hrs and seconds are left for the event.
How can I do that, please help me.
It would be a great help if i can get a similar kind of sample code.
Many Thanks in advance.
iPhone Developer
Maybe It can be helpful to you - http://blog.webscale.co.in/?p=244
Basically you want to use NSTimeInterval and NSDate to calculate the difference in time. For example:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSDate *now = [NSDate date];
NSDate *futureDate = [dateFormat dateFromString:#"07/15/2015"];
// Now we can calculate the time interval, which really is an integer
// This is the number of seconds between the 2 dates, so with math you can calculate
// what you need. Remember, when you do dateFromString, the time is midnight 00:00:00
// however, *now is set to the current time. You may want to work on that a bit
NSTimeInterval timeDifference = [futureDate timeIntervalSinceDate:now];
// Also note, if you swap the order and do now timeIntervalSinceDate:futureDate, you
// get a negative number.
Related
Hi I am creating an NSDate which I am using to set a Picker, but when I output the picker date to NSLog it is always an hour behind the time shown in the actual picker.
Also as a test I noticed that the code:
NSDate *now = [NSDate date]; //should give me the current date and time on my emulator
NSLog(#"Date and Time now: %#", now);
The NSLog value is always 1 hour behind the time shown on my emulator.
My question is why?
Thanks in advance :)
UPDATE --------------------------------------------------------------------------------
I did a couple of more tests and it turns out that NSDate using the NSGregorian Calendar was returning the correct time and then NSDate using the currentCalendar was off by 1 hour.
So my new question is why is that? I have checked the settings on my emulator and the device has its calendar set to Gregorian. Could this be due to a timezone difference? If so then is there a way for me to set the picker to use the same timezone as the users device?
Thanks
I think it is because your simulator time is set to default time zone (EN). NSDate is always set from your local time. When you try it on your device it will be correct.
i have this code in my project and work fine:
NSDate*now = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd.MM.yyyy"];
i create date and store it to my CoreData. Always that time will my actual time on my device.
Congrats to your new iPhone anyway. Welcome to big Apple Family! :)
I have to convert a Double value into a Date value in Objective-C
I tried many ways but im not getting it.
date=var1/24;
Here var1 is a double value which should be divided by 24 and stored as a Date into the variable date. How can I do this using Objective-C?
I created the date variable like this:
NSDate *date=[[NSDate alloc]init];
date=(nsdate)var1/24;
How can I do this?
Its a Double Variable.. which will be containing values upto 24 it will be representing HOURS from TODAY..
OK, so you have a relative value that you want to add to an absolute value. Additional work is required.
First, you must decide "What is today?". Is it 12:01am? If it is, in which time zone? GMT? Something else? You have to know this, because 12:01am GMT is not the same thing as 12:01am EDT. So: what is today?
Once you've decided where you're going to be measuring time from, you have to construct an NSDate representing that point in time.
For example:
NSDate *rightNow = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSUIntegerMax fromDate:rightNow];
This will give you an NSDateComponents object, which is an object that represents a point in time relative to a calendar. In this case, we're using the "current calendar" (probably the Gregorian calendar, but not necessarily), and the default time zone is your current time zone. If you need to have it be relative to a different time zone, you can create a new NSTimeZone object and use -[NSCalendar setTimeZone:] to set the calendar's time zone (before asking for the date components).
Now that you've got the date components, we can "reset" things to the appropriate time:
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
Then we can turn it back into an NSDate to make it an absolute point in time:
NSDate *startingPoint = [calendar dateFromComponents:components];
NOW we have our starting point, and can deal with the "hours from today". First, we'll create a date components object to represent however many hours the difference is:
NSInteger hourDelta = var1 / 24;
NSDateComponents *delta = [[NSDateComponents alloc] init];
[delta setHour:hourDelta];
Now, we'll add this relative difference to our absolute starting date:
NSDate *finalDate = [calendar dateByAddingComponents:delta toDate:startingPoint options:0];
And because we're good citizens, we'll clean up our memory (unless you're using Garbage Collection or compiling with ARC):
[delta release];
Some important notes:
All of the manipulations are done via the NSCalendar object, because the NSCalendar is what defines what a "day" means and what an "hour" is. You think "there are 24 hours in a day and 60 minutes in an hour...", but that's not necessarily true. I can create my own calendar that has 10 hours in a day, and 10 minutes in an hour. If I want, I can define a "day" as something other than "one full rotation of the Earth". The NSCalendar define all these rules. Thus, all relative manipulations of dates (adding "hours" and "days" or whatever) must be done via the calendar.
There are methods on NSDate like -dateByAddingTimeInterval:, but this is for when you're dealing with absolute intervals and not relative amounts.
It depends of what you want to do exactly, but a direct cast as (nsdate)var1/24 will definitely NOT work!!!
Anway, what does your variable var1 represent exactly? Minutes ? Seconds ? Hours ? From which reference date? Today? The UNIX Epoch? Is it a UNIX timestamp (seconds since 01/01/1970)? Just asking to "convert a number to a date" means nothing on its own ;-)
Depending on the answer to those questions, you may use either NSDateComponents to produce a date giving the different date components (month, day, hours, minutes, seconds, …), or create a NSDate from a UNIX timestamp using dateWithTimeIntervalSince1970... or use any other method from NSDate or NSDateComponents depending on your needs.
Whatever your problem is, do read* the Date and TIme Programming Guide!! Everything is explained here about date manipulation; it will contain everything you need to answer your question.
I am confused regarding to calculation of two different times. In my game, when game starts then timer gets started (like stop watch) and it stops when game gets finished. Now I have to store best low time among previous time list.
I am getting time in hh:mm:ss format. how can I store this time so that i can compare it with different time in list ? I tried to store this value in NSString, but the comparison fails.
EDITED :
Let me clarify the Question :
For example how can I store different times from stopwatch and how to sort it in ascending order ?
any suggestions?
Thanks...
Take two NSDates, one at the game start and one at game finish, then calculate the difference.
NSDate *startDate = [NSDate date]; // At game start
NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:startDate]; // At game finish
NSlog(#"interval: %.2f", interval);
You could use
long stamp = (long)[[NSDate date] timeIntervalSince1970];
for each of your time-relevant situation since the posted code is giving you a UNIX-timestamp. This timestamp can be used in arithmetic operations/comparisons which should be exact what you are looking for.
I have an array of NSDates which I build from strings using [NSDate dateFromString]
In the xml I parsed to get the string there was also a timezone string. As far as I can see in the manual NSDate does not in it self deal with timezones. Do I need to always store this timezone value somewhere and pair it with the belonging NSDate each time I need it?
I also need to figure out that if an event starts in London at 10:00, but I am in Denmark having my iPhone set to danish time my "event started in London" should display at 09:00 o'clock.
Again if an event starts in London at 10:00 o'clock and ends in Denmark at 12:00 o'clock, If I were to compare start time and end time using an iPhone with danish settings I would get that the duration of the event was 02:00 event though 10:00 o'clock in UK and 12:00 o'clock in Denmark is only 1 hour apart.
NSdate works really well for these things in the scope of one timezone, but introducing the timezone part just made everything complicated to me. Is there a way to abstract/hide all these calculations, as I see potential for making a lot of mistakes.
I have been through the NSDateformatter and NSDate guides from Apple, but they are really vague and sports a substantial amount of deprecated code :/
Thanks for any help given.
You should take one standard timezone like UTC/GMT format for all calculation.
According to the NSDate reference, dateWithString: takes an offset to GMT as last component; while it is not a time zone, it is sufficient to perform computation or comparison).
Looking at the NSTimeZone reference, you can use the abbreviationForDate: and the timeZoneWithAbbreviation: to get a NSTimeZone object from a NSDate instance. Once you get the time zone, you have everything you need.
I convert the present date and the date I would like to know if is close, to GMT and then returning the difference. So I changed every thing to deal with differences instead of actual times and dates. A bit like a music score transposed to a different key:)
+ (NSInteger) minutesUntilDate:(NSDate*) date withTimezoneOffset:(NSInteger) GMTOffset
{
NSDate *now = [NSDate date];
NSTimeInterval localTimeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
now = [now addTimeInterval:(localTimeZoneOffset * -1)];
date = [date addTimeInterval:(GMTOffset * 60 * 60) * −1];
return ((NSInteger)[now timeIntervalSinceDate:date] / 60 ) * -1;
}
As soon as you have allocated an NSDate, these do not have timezone information any longer. NSDate is "timezone-less" and is always in GMT. You should make sure that NSDate understand your format correctly when allocating it.
Once you have an NSDate you can make normal calculations and ignore the timezones.
You only need to take care of timezones when reading strings into NSDates and when printing them out.
For PDT, I would want "-0700".
I'm getting a date in the past to determine how long ago something happened.
NSDate *then = [NSDate dateWithString:#"1976-04-01 12:34:56 -0700"]; // Note the hard-coded time zone at the end
I'll be constructing the date string elsewhere but I don't know how to access the local time zone.
I read the Apple Dates and Times Programming Topics for Cocoa as well as the NSTimeZone and NSDate Class References but it's just too hard for me to put the information together. I could really use a few lines of code just to show how it's used.
Update: While struggling with this, I was writing code using a Command Line template so I could try things quickly. I just tried my previous code on iPhone and I'm getting NSDate may not respond to '+dateWithString:' Sorry if that added to the confusion, who knew Apple would change up such a basic class.
Use NSDateFormatter to build NSDate from a string:
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSDate *formatterDate;
formatterDate = [inputFormatter dateFromString:#"1976-04-01 12:34:56 -0700"];
NSString *dateString = [inputFormatter stringFromDate:formatterDate];
NSLog(#"date:%#", dateString);
This way you get the local time from string, for example the date specified by the string:
"1976-04-01 12:34:56 -0700"
is in time zone -0700, (I'm in time zone GMT +1000) so I get:
2009-11-17 22:13:46.480
cmdline[10593:903] date:1976-04-02
05:34:56 +1000
The time zone offset is dependent on the date in much of the world—those parts of it that use Daylight-Saving Time/Summer Time.
The only correct way is to generate the entire string from date and time-zone together. Use NSDateFormatter for this.
The best way is to probably use a simple calendar formatter
NSCalendarDate * date = [NSCalendarDate calendarDate];
[date setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"PDT"]];
NSLog([date descriptionWithCalendarFormat:#"%z"]);
which will output '-0700'
or leave out the second line if you want the current time zone of the system (not sure which you were asking for)