This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to Get time difference in iPhone
I´m getting date and time from a JSON feed. I need to find the difference between the date I´m getting from the feed and today´s date and time. Any suggestions how I can do this?
I know I need to subtract the current date with the date I get from the feed, but I don´t know how to do it.
Ex:
Date from feed: Date: 2011-06-10 15:00:00 +0000
Today: Date: 2011-06-10 14:50:00 +0000
I need to display that the difference is ten minutes.
Thanks!
Create two NSDate objects from the strings using NSDate's -dateWithString:, then get the difference of the two NSdate objects using
NSTimeInterval diff = [date2 timeIntervalSinceDate:date1];
You need to convert the input date to an NSDate object before you try and compare.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss +0000"];
NSDate *startDate = [dateFormatter dateFromString:yourJSONDateString];
NSDate *endDate = [NSDate date];
CGFloat minuteDifference = [endDate timeIntervalSinceDate:startDate] / 60.0;
The formatter assumses the UTC offset will always be zero. If this isn't true, see Microsoft's date format string page for other format codes you can use.
--
Edit: the dateWithString method that everyone else used will be better to use in your situation, but the date formatter is necessary if the date format string you are getting isn't exactly right. I don't think I've ever used an API that sent dates in the correct format, perhaps I'm just unlucky :-(.
From below code you will get an idea for comparing two NSDate objects.
NSDate *dateOne = [NSDate dateWithString:#"2011-06-10 15:00:00 +0000"];
NSDate *dateTwo = [NSDate dateWithString:#"2011-06-10 14:50:00 +0000"];
switch ([dateOne compare:dateTwo])
{
case NSOrderedAscending:
NSLog(#”NSOrderedAscending”);
break;
case NSOrderedSame:
NSLog(#”NSOrderedSame”);
break;
case NSOrderedDescending:
NSLog(#”NSOrderedDescending”);
break;
}
Related
This question already has answers here:
How do I add 1 day to an NSDate?
(30 answers)
Closed 10 years ago.
Here is the code from where I can get todays date as a string:
NSString *string;
NSDateFormatter *formatter;
string = [formatter stringFromDate: [NSDate date]];
formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat: #"yyyy-MM-dd "];
string = [formatter stringFromDate: [NSDate date]];
But now I want such that I will put this string as a parameter and a method will return the date of the day after 10 days of this date as a string. But I couldn't find any solution for it. Can anybody help me?
My answer will be a bit longer and probably slightly OT but I think it is better to provide you a knowledge of the concepts inside date management instead of a "copy and paste" answer.
Date management in fact even if intuitive is a quite complex task. In order to do this properly with Cocoa you must understand a few basic concepts.
The "date" concept itself is just a numerical representation of how many seconds elapsed from a reference date. This is an absolute measure and nothing can change it: if you say that now is time 0, in 10 seconds it will be time 10, and so on. It is represented by Cocoa with "NSDate".
Now to translate the "numerical date" to a "calendar date" you need to apply this numerical date to a "calendar" ("NSCalendar" Cocoa class). Clearly there are many types of calendars around so what you have to do is to pick the right calendar you want to use and then apply the numerical date to it: the effective result will be a "calendarized date". Note that the same "numerical date", which is common to all calendars as it is an absolute measure, will provide different results on different calendars. A calendar is all in all a complex algorithm or table that maps every single numerical date to a specific "calendar date".
The components that make a calendar date are called "date components" and are represented by the Cocoa class "NSDateComponents". As you may have understood, you cannot directly put in relation a "Date component" with a "Date" but you need to mediate them through the "Calendar". That's why all methods that put in relation the "Date" and "NSDateComponents" classes are defined in the "NSCalendar" class and this explains why a specific "NSDateComponents" instance is associated to a specific "NSCalendar" instance.
Finally your last step is to convert the "date component" to a "human readable format". To do this you use the "NSDateFormatter" object. While it would be more appropriate to link the date formatter to the date components, in order to facilitate the translation from a date to a string and vice versa NSDateFormatter methods play directly with NSDate objects instead of NSDateComponents. Obviously the NSDateFormatter class must be associated to a specific calendar (and be careful: it is initialized with a default calendar).
Now that you have this baggage of information you can easily understand how to proceed. Your task is to convert a date in "string format" to a date, in the same format, after 10 days.
So the tasks to be accomplished are (the code is below):
1. identify the Calendar you want to use
2. create a NSDateFormatter that accepts your input string and link the Calendar to it
3. use NSDateFormatter to import the string to a "NSDate"
4. use the NSCalendar to convert the date to a NSDateComponents object
5. add 10 days to the "day" component of NSDateComponents; don't take care of "end of month" or "end of year", because NSDateComponents + NSCalendar know how to do it!
6. use NSCalendar again to convert the new recalculated NSDateComponents instance to NSDate
7. use the NSDateFormatter you defined before to convert the new NSDate to a NSString.
You may ask: why I cannot just sum to my imported NSDate 10*24*60*60 seconds? while in most cases this solution will work, there are some cases where this operation will provide an incorrect result. E.g. in the daylight saving switch you revert the clock by 1 hour, that is 60*60 = 3600 seconds. This means that in your Calendar a 1 hr range of seconds will be mapped to two different date/times (1 hr before and 1 hr after the switch). This information is not known to NSDate but it is known by NSCalendar. You can visually see what's happening in this way: imagine an infinitely long line (the line of time) where every single "tick" in the line is 1 second. If you keep the "point in time" where you are now this tick will be associated to a specific date and time in your calendar and clock. Imagine now to identify the point in this timeline where you do the daylight saving switch and suppose you need at that time to revert your clock to 1 hour before. What you do is to cut the timeline in two pieces, then take the second half and overlap its first hour with the last hour of the first half. You will see then that the time is still going on but your calendar in this 1 hour overlap will be associated to two given range of times! this is an information known to your calendar + locale + time zone only, not to NSDate alone (by the way I intentionally skipped any discussion here about the "time zones" and "locale": they're relevant because time zone takes care of associating an absolute time to a effective time of day, while the locale can change some calendar rules, e.g. the daylight saving switch).
NSString *startDateStr = #"2013-02-25";
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.calendar=calendar;
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *startDate = [dateFormatter dateFromString:startDateStr];
NSDateComponents *startComponents = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:startDate];
startComponents.day+=10;
NSDate *endDate = [calendar dateFromComponents:startComponents];
NSString *endDateStr = [dateFormatter stringFromDate:endDate];
NSLog(#"Date %# + 10 days gives %#",startDateStr,endDateStr);
Note that the above calculations could have been simplified using the NSCalendar's dateByAddingComponents:toDate:options: but I preferred the first method to give you a better picture of the interaction between the classes.
NSDate *now = [NSDate date];
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*10];
This will return date after 10 days.
Convert your fromDate string to a Date type and use the below function and pass the days parameter as 10:
NSString *fromDateString = #"Your_date_string";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YOUR_DATE_FORMAT"];
NSDate *fromDate = [dateFormat dateFromString:dateStr];
[dateFormat release];
+ (NSDate *) getDate:(NSDate *)fromDate daysAhead:(NSUInteger)days
{
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = days;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *previousDate = [calendar dateByAddingComponents:dateComponents
toDate:fromDate
options:0];
[dateComponents release];
return previousDate;
}
Code for 10 days after date ::
NSDateFormatter *entryDateFormat;
entryDateFormat = [[NSDateFormatter alloc]init];
[entryDateFormat setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSString *s = [NSString stringWithFormat:#"%#", [entryDateFormat stringFromDate:[[NSDate date] dateByAddingTimeInterval:60*60*24*10]]];
NSLog(#" --> %#", s);
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
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Converting an ISO 8601 timestamp into an NSDate: How does one deal with the UTC time offset?
I am writing an iPhone app, which brings time from Ruby on Rails web service.
The time string i get from JSON response has following format.
"2012-12-01T01:01:00Z"
I want to get system time zone based time from this.
How can I do?
If you need your times to match on server and app, you can just set the time zone of your date formatter you use for converting the JSON date string to an NSDate to use GMT when you get it from the web service. So your date formatter should be initialized like this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-dd'T'HH:mm:ss'Z'"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
Then get your date string from the JSON and create a date with it:
NSDate *dateFromServer = [dateFormatter dateFromString:[json valueForKey:#"created_at"]]
// Do something with dateFromServer like save it to CoreData
Then, later on, when you want to display that date, just create another date formatter that you want to use to display the date in your local time. NSDate will default to the system timezone and it should display the correct time.
NSDateFormatter *displayDateFormatter = [[NSDateFormatter alloc] init];
[dispalyDateFormatter setDateFormat:#"MMM dd, YYYY"]; // ex. Jul 21, 2012
NSDate *dateFromCoreData = [managedObject valueForKey:#"CreatedAt"];
NSString *dateString = [displayDateFormatter stringFromDate:dateFromCoreData];
// Display your date string in a UILabel or Table View Cell, etc.
Best regards.
I want to present a date to the user of my app as "Today", "Yesterday" or as a formatted date (i.e. 27/05/2011). Is there a quick way to get "Today" or "Yesterday" based on a given NSDate? If not I can write the code myself, I am just curious if I am overlooking some simpler way than working out remaining hours manually.
If you just want to present date to your user, there is an option in NSDateFormatter right for that.
- (void)setDoesRelativeDateFormatting:(BOOL)b
Take a look at documentation for more information.
Check out this similar question: Compare NSDate for Today or Yesterday.
You make NSDate objects from today and yesterday, and then compare the first 10 characters of their description to the NSDate you're unsure of.
From the Date and Time Programming Guide:
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *today = [[NSDate alloc] init];
NSDate *tomorrow, *yesterday;
tomorrow = [today dateByAddingTimeInterval: secondsPerDay];
yesterday = [today dateByAddingTimeInterval: -secondsPerDay];
[today release];
In my date picker i can select a date from the list.
I save it in my string pickUpDateTime
self.pickUpDateTime = [NSString stringWithString:[apiFormat stringFromDate:d]];
I'm having a problem where the user is able to pick a date in the past. Is there some way to get the current day and check that its in the future?
My string holds the date like this 2010-11-04.
The user shouldnt be able to select a day in the past or the current day.
Thanks
-Code
You can get the current date and time with:
NSDate *now = [NSDate date];
Compare the 2 dates with:
if ([d compare:now] == NSOrderedDescending) {
// d is later than now
} else {
// d is earlier than or equal to now
}
If you're using a UIDatePicker, just set
datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:24*3600];
e.g. to allow dates starting tomorrow. Working back from the date string "2010-11-04" to a NSDate object is possible but cumbersome. (but if you insist, have a look at NSDateFormatter)
Lots of answers above give good advice about working with NSDates in general; things are a tiny bit more complicated if you want to round to the start of the day to say e.g. 'at least tomorrow' rather than 'at least 24 hours away'.
In general terms:
get an instance of NSCalendar to represent the Gregorian calendar
use the NSCalendar to convert an NSDate into an NSDateComponents representing just the day, month and year
use the NSCalendar to convert the NSDateComponents back into an NSDate
use arithmetic as recommended elsewhere to increment the NSDate a day into the future, for example
I have to dash, but relevant methods are:
NSCalendar +currentCalendar or -initWithCalendarIdentifier:NSGregorianCalendar to be extra safe
NSCalendar -components:fromDate: (the first parameter is a flag field indicating which bits of the date you need to be filled in) and -dateFromComponents:
NSDate -timeIntervalSinceDate:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
NSString *tempStr=[NSString stringWithFormat:#"%#",[df stringFromDate:datePicker.date]];
txtBirth.text=tempStr;
NSString *birthDate = tempStr;
NSDate *todayDate = [NSDate date];
int time = [todayDate timeIntervalSinceDate:[df dateFromString:birthDate]];
int numberOfDays = time/86400;
hear number of data return data difference.....