I have problems printing a date as NSString. I have stored current date and time at certain points of my app lifecycle this way:
NSDate *current = [NSDate date];
long currentTime = [current timeIntervalSince1970];
Now, I need to show those dates in UILabels. I tried this way:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:currentTime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy - HH:mm:ss"];
NSString *stringFromDate = [formatter stringFromDate:date];
but I'm not getting the correct date nor the time. What could I be missing?
Thanks!
Try this,
NSString *stringFromDate=[NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
also you can change the datestyle and timestyle.
Your currentTime variable is a long, and not an NSTimeInterval (a double). You are losing not only the fractional part (less important), but the upper range of the time interval. Change it to:
NSTimeInterval currentTime = [current timeIntervalSince1970];
Related
Suppose, my birthdate is (mon/day/year) 10-05-1932 (as NSDate), how to convert this to NSTimeInterval.
Again, how to convert back that NSTimeInterval to NSDate back?
I tried using different methods of NSDate but haven't succeed yet.
What I'm doing?
NSString *strdate = #"10-05-1932";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM-dd-yyyy"];
NSDate *date = [df dateFromString:strdate];
NSLog(#"%.f", -[date timeIntervalSinceNow]);
This logs 2616605071 (as on 4th September 2015 at 16:21) – When I checked it with the site like this it gives me wrong date.
NSTimeInterval timeInterval = date.timeIntervalSinceReferenceDate;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate: timeInterval];
Try the code below. date and anotherDate will be identical.
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:10];
[components setMonth:5];
[components setYear:1934];
NSDate *date = [calendar dateFromComponents:components];
NSLog(#"%#", date);
NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
NSLog(#"%#", anotherDate);
UPDATE:
It's incorrect because you get timestamp (time interval) from that website which use UNIX timestamp. Also, it's incorrect because you use timeIntervalSinceNow which will likely change every time you call the method because it's relative to the current time. If you want the date/time interval that compatible with that website. Use:
NSTimeInterval timeInterval = date.timeIntervalSince1970;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
You can copy the timeInterval from the code above (-1188000000) and paste it on the website and it will give you a correct date.
Internally, NSDate store time interval relative to reference date (Jan 1st, 2001). The website you mentioned is UNIX timestamp that relative to Jan 1st, 1970.
This is just worked!
NSString *strdate = #"10-05-1932";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM-dd-yyyy"];
NSDate *date = [df dateFromString:strdate];
NSLog(#"%#",date);
NSTimeInterval interval = [date timeIntervalSince1970];
NSLog(#"%f", interval);
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:interval];
NSLog(#"%#",date2);
Thanks to #sikhapol
I have this date object from Parse, "2015-07-24 20:36:38 +0000" and I would like to compare it to today's date to see how much time has passed since the date on the date object. Any ideas how to do this?
I have this method I use to get the hour and minute, but I'm stuck on how to use this to compare dates outside of the current day.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm"];
NSString *formattedTime = [dateFormatter stringFromDate: date];
You can use an NSTimeInterval for this, the code is:
NSTimeInterval timeInterval = [date timeIntervalSinceNow];
with date being the date from parse as an NSDate, not NSString. and there should be no need to format it before comparing. Hope this helps
If you want this formatted as a string, in iOS 8 and later you can use NSDateComponentsFormatter:
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitMinute | NSCalendarUnitHour;
NSString *string = [formatter stringFromDate:date toDate:[NSDate date]];
So i am getting a string containing date and time in this format "2014-12-22T11:00:00+0500" Now in order to convert it into NSdate i am using
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate* date = [dateFormatter dateFromString:start_time];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString* temp = [dateFormatter stringFromDate:date];
self.eventDate = [dateFormatter dateFromString:temp];
NSDateFormatter* timeFormatter = [[NSDateFormatter alloc]init];
[timeFormatter setDateFormat:#"HH:mm:ss"];
NSString* temp2 = [timeFormatter stringFromDate:date];
self.start_time = [timeFormatter dateFromString:temp2];
Now even though the conversion is successful the problem is that eventDate also has has time after date 00:00:00. How can i remove this so that eventDate only contains date.
Conversly start_time has the time of event but also has some arbritrary reference date before that. How can i remove that so i only have time in start_time
I have searched hard and fast but haven't been able to figure out this problem. Any help would be appreciated.
You cannot remove either the date or the time to keep only one component. If I remember correctly NSDate object is internally just a number of seconds relative to a fixed point in time. So every NSDate contains the full date and time information.
What you probably want to do is to get the NSDateComponents you want from a NSDate object.
Instead of trying to store this separate, just display these dates separate. I think it could be useful sometimes to get the date completly, but i don't know your idea.
You can try with it, it may be help you.
NSString *finalDate = #"2014-12-22T11:00:00+0500";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [dateFormatter dateFromString:finalDate];
//For getting Time
NSDateFormatter* df1 = [[NSDateFormatter alloc]init];
[df1 setDateFormat:#"hh:mm:ss"];
NSString *time = [df1 stringFromDate:date];
NSLog(#"time %# ", time);
//For getting Date
NSDateFormatter* df2 = [[NSDateFormatter alloc]init];
[df2 setDateFormat:#"yyyy-MM-dd"];
NSString *actualDate = [df2 stringFromDate:date];
NSLog(#"actualDate %# ", actualDate);
I have two strings coming from my server in which I store the time, and I need to compare the time interval between those two, in minutes, and if it's necessary, in hours. Should I convert to NSDate or use NSString?
The NSStrings look like:
NOW 14:22
LAST TIME 10:18
EDIT #1
Since everyone is saying me to use NSDate, i converted the data in my database to DATETIME, and now i can compare the two NSDate using the following code :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"pt_BR"]];
[dateFormatter setDateFormat: #"yyyy-MM-dd HH:mm:ss"];
NSDate *currentDateTimeWithOffset = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone] secondsFromGMT]];
NSString *strDate = [dateFormatter stringFromDate:currentDateTimeWithOffset];
NSDate * now = [dateFormatter dateFromString:strDate];
NSDate *date = [dateFormatter dateFromString:#"2013-04-09 12:10:18"];
NSLog(#"Difference %f",[now timeIntervalSinceDate:date]);
And the result is the following :
Difference 864.000000
NOW 2013-04-09 15:24:42 +0000
LAST DATE 2013-04-09 12:10:18
Is that correct? the Difference is in Seconds?
If the format gets more complex than the one you've shown, consider using NSDateFormatter. For the simple example:
NSArray *hoursMins = [timeString componentsSeparatedByString:#":"];
NSInteger timeInMins = [hoursMins[0] intValue] * 60 + [hoursMins[1] intValue];
Then subtract the two times in minutes. The date formatter approach looks like this:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm"];
NSDate *date = [df dateFromString:timeString];
You can get a difference in seconds between two dates using:
[date timerIntervalSinceDate:anotherDate];
NSDateFormatter is the "clean" way to do it. But if you are looking for quick and dirty, and those are the actual strings you are getting (that include the NOW and LAST TIME), I'd just use a specific NSRange to pull the hours and minutes out and compare them.
Make sure, though that you check the hours, and if the "now" hour is before the "last time" hour, you add 24 to the now to throw in the day rollover.
With only NSString, NSDateFormatter is used to get NSDate
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
If you had separate values for hours, minutes and seconds you could use NSCalendar
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1965];
[comps setMonth:1];
[comps setDay:6];
[comps setHour:14];
[comps setMinute:10];
[comps setSecond:0];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];
And a perfect solution would be to use timestamps instead of NSString. Not only it's easy to convert timestamps to NSDate (NSDate +dateWithTimeIntervalSinceReferenceDate)and then to NSString when needed, but you can also get the time difference by subtraction.
And with two NSDate objects the time difference is calculated with NSDate -timeIntervalSinceDate.
I would like to compare the current date with another date, and if that is date is earlier than the current date, then I should stop the next action. How can I do this?
I have todays date in yyyy-MM-dd format. I need to check this condition
if([displaydate text]<currentdate)
{
//stop next action
}
Here if displaydate is less than todays date then it has to enter that condition.
NSDate *today = [NSDate date]; // it will give you current date
NSDate *newDate = [dateFormatter dateWithString:#"xxxxxx"]; // your date
NSComparisonResult result;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
result = [today compare:newDate]; // comparing two dates
if(result==NSOrderedAscending)
NSLog(#"today is less");
else if(result==NSOrderedDescending)
NSLog(#"newDate is less");
else
NSLog(#"Both dates are same");
got your solution from this answer How to compare two dates in Objective-C
Alternative to #NNitin Gohel's answer.
Compare using NSTimeInterval ie NSDate timeIntervalSince1970:
NSTimeInterval *todayTimeInterval = [[NSDate date] timeIntervalSince1970];
NSTimeInterval *previousTimeInterval = [previousdate timeIntervalSince1970];
if(previousTimeInterval < todayTimeInterval)
//prevous date is less than today
else if (previousTimeInterval == todayTimeInterval)
//both date are equal
else
//prevous date is greater than today
You can have a closer look at this Tutorial about NSDateFormatter and when you have your NSDate object you can compare it to another NSDate and get an NSTimeInterval which is the difference in seconds.
NSDate *nowDate = [NSDate date];
NSTimeInterval interval = [nowDate timeIntervalSinceDate:pastDate];
Some methods of NSDate class are:
isEarlierThanDate. // using this method you can find out the date is previous or not..
isLaterThanDate
minutesAfterDate.
minutesBeforeDate. etc..
also see this link with many methods of NSDate in iPhone SDK..
how-to-real-world-dates-with-the-iphone-sdk
Update
//Current Date
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
use this bellow method for convert NSString date to NSDate format just paste this method in your.m file
- (NSDate *)convertStringToDate:(NSString *) date {
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd"];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", date);
date = [date stringByReplacingOccurrencesOfString:#"+0000" withString:#""];
nowDate = [formatter dateFromString:date];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", nowDate);
return nowDate;
}
after that when you want to use it just use like bellow..
NSDate *tempDate2 = [self convertStringToDate:yourStringDate];
and then try to compare like this..
if (tempDate2 > nowDate)