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
Related
I have a NSString which have the format of #"2013-01-09 06:10:10 +0000" (I am getting it from server and it is not the current time). I want to increment it by one second continuously. I can use a timer for doing it, but how to increment the time by one second?
Try this,
NSDate *correctDate = [NSDate dateWithTimeInterval:1.0 sinceDate:yourDate];
You can get yourDate from string using NSDateFormatter.
Nowadays (2017) Apple recommends to use (NS)Calendar for all kinds of date math
Objective-C
NSDate *now = [NSDate date];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDate *nowPlusOneSecond = [currentCalendar dateByAddingUnit:NSCalendarUnitSecond
value:1
toDate:now
options:NSCalendarMatchNextTime];
Swift 3
let now = Date()
let currentCalendar = Calendar.current
let nowPlusOneSecond = currentCalendar.date(byAdding: .second, value: 1, to: now)!
add 1 second in your date like bellow..
NSDate *mydate = [NSDate date];
NSTimeInterval secondsInEightHours = 60; // you can add hours and minuts with multiply the numbers with this second..
NSDate *dateEightHoursAhead = [mydate dateByAddingTimeInterval:secondsInEightHours];
Say your date string is in var called serverString. You can get a date this way...
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd hh:mm:ss z"];
NSDate *date = [df dateFromString:serverString];
And increment it this way:
date = [date dateByAddingTimeInterval:1.0];
SWIFT 3.x Solution
// Just an example to present second level date/time calculation
let time = NSDate()
let interval:Double = 5.0
let timeFiveSecondLater = time.addingTimeInterval(interval)
I've searched and haven't found an exact question like mine, so here goes nothing:
I have a NSString containing a key that I pull from an XML feed. The key is a time in 24-hour format (e.g. 13:30 or 15:00.) I'd like to convert the NSString to an NSDate and have it converted to the appropriate timezone based on the device's set timezone. The key is Unicode HH:mm (24:00), so I'm curious why this does not work as it should.
I've already gotten a basic outline that should work, but alas does not. The 2nd NSLog (Got NS Date) returns null and the final log returns a strange number (1969-12--2147483629 -596:-31:-23 +0000 to be precise.) What am I doing wrong here?
Thanks in advance,
NSString *dateString = [dict objectForKey:#"24hrdate"];
NSLog(#"NSString Date: %#", dateString);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm"];
NSDate *sourceDate = [formatter dateFromString:dateString];
NSLog(#"Got NS Date: %#", sourceDate);
NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone *destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
NSLog(#"Final Date: %#", destinationDate);
First of all understand that the date component will be 01-01-1970 because it isn't provided. I am assuming that you want the time to be 04:00 GMT if the input string is #"04:00". That you can achieve by setting the time zone of the formatter.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
[formatter setDateFormat:#"HH:mm"];
NSDate *sourceDate = [formatter dateFromString:dateString];
NSDate is used to represent a date and time. While you can represent just a date by sticking with midnight, you can't really represent just a time of day with it. You can sort of fake this on the Mac (it defaults to some reasonable day), but on iOS you'll get wildly inaccurate times instead. (At least, you do on certain versions. This may have been fixed.)
There's two approaches here:
You can build a NSDateComponents from your time of day and using dateByAddingComponents to add that to midnight on the date you want the time to appear on. This will fail to return the time you expect on a day where daylight savings begins or ends.
You can build a date/time string using the date you want (NSDate) and the time (likely, as a NSString).
- (NSDate *)timeInHours: (NSInteger)hours
minutes: (NSInteger)minutes
seconds: (NSInteger)seconds
onDate: (NSDate *)inDate;
{
id timeStr = [[NSMutableString alloc] initWithFormat: #"%02d:%02d:%02d", hours, minutes, seconds];
id dateStr = [dateWithoutTimeFormatter stringFromDate: inDate];
id dateTimeStr = [[NSString alloc] initWithFormat: #"%# %#", dateStr, timeStr];
[timeStr release];
id dateTime = [dateWithTimeFormatter dateFromString: dateTimeStr];
[dateTimeStr release];
return dateTime;
}
If you really want just the time of day, just keep it around as a string.
Just wanted to post back that I did manage to achieve what I initially set out to do without any issues. Basically, I had to convert the string to NSDate, run that NSDate through a NSDateFormatter (set to the time's original timezone--NSDateFormatter's setTimeZone was helpful), pull an NSDate out of that, and then run that through another NSDateFormatter for the device's timezone. I then converted the resulting NSDate back to NSString, and stuck it on a UILabel.
This solution seems to have worked quite well, as I've set my devices to various timezones, and the timezone change is still correct.
EDIT: this was important to included, too:
NSString *date…….
date = [date stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
i am not able to get proper time from a given time.
My code is as follows
NSArray * array_TimeSlotWith_StartDate = [ #"01/05/2010 10:15:33" componentsSeparatedByString:#" "];
NSArray * array_TimeSlotWith_EndDate = [ #"01/05/2010 10:45:43" componentsSeparatedByString:#" "];
NSLog(#" array_TimeSlotWith_StartDate === %#",array_TimeSlotWith_StartDate);
NSLog(#"array_TimeSlotWith_EndDate == %#",array_TimeSlotWith_EndDate);
NSArray * Array_StartTime = [[array_TimeSlotWith_StartDate objectAtIndex:1] componentsSeparatedByString:#":"];
NSLog(#"Array_StartTime == %#",Array_StartTime);
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:#"HH:mm:ss"];
NSDate *date1 = [df dateFromString:[array_TimeSlotWith_StartDate objectAtIndex:1]];
NSDate *date2 = [df dateFromString:[array_TimeSlotWith_EndDate objectAtIndex:1]];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
NSLog(#"date 1%#",date1);
NSLog(#"date 2%#",date2);
It gives me value of date 1 as 1970-01-01 04:45:33 +0000 instead of this what i need is just the time an that should be 10:15:33.
And same for the end date also it gives log as 1970-01-01 05:15:43 +0000 instead of this it should output as only the time component with value 10:45:43 .
Time doesn't exist without a date. If you don't specify any date, the date formatter will default to "1970-01-01"(Unix epoch). I hope this SO link will help you.
Though the date1 and date2 don't contain the value you've expected, I feel that, interval should contain the correct result you need. I suggest you to just ignore the dates in this context.
you neither specifying the date and timezone that's the reason NSDate object pick the default one for its use.
How can I compare the dates only, not the time. I am using
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *tempDate = #"2-2-2012"; //Dynamic Date
NSDate *dateString = [dateFormatter dateFromString:tempDate];
NSLog(#"%#",dateString);
It logs this: 2012-02-01 18:30:00 +0000
NSDate *now = [NSDate date];//Current Date
NSLog(#"%#",now);
It logs this: 2011-04-04 14:49:45 +0000
I want to compare Dynamic date and current date, I don't need time. I may not using the correct NSDateFormatter. Can anyone of you tell me how to do this? If I am not clear, please let me know.
Suppose I have to strings
date1 = 3-2-2011;
date2 = 4-5-2020;
I want to convert them in date, only after that I can compare them. Its not happening from my date Formatter. Please have a look.
Thanks!
Simplest way is to compare date by converting it into string.
Sample Code is as shown below:
//Current Date
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
NSString *dateString = [formatter stringFromDate:date];
[formatter release];
//Other Date say date2 is of type NSDate again
NSString *date2String = [formatter stringFromDate:date2];
//Comparison of Two dates by its conversion into string as below
if([date2String isEqualToString:dateString])
{
//Your logic if dates are Equal
}
else if(![date2String isEqualToString:dateString])
{
//Your Logic if dates are Different
}
EDIT:
Checkout this link.
Comparing dates
http://www.iphonedevsdk.com/forum/iphone-sdk-development/64625-how-compare-2-dates.html
Hope This Helps You. :)
Use NSCalendar and NSDateComponents to get a date components object. Then you can look at only those parts of the date that you care about.
If you're just trying to determine whether two dates are the same, regardless of time, one way to go is to use NSDate's -timeIntervalSinceDate: method. If the time interval returned is less than 86,400 seconds (i.e. 24 hours * 60 minutes * 60 seconds) then you can feel fairly sure that it's the same day. Changes related to such things as daylight savings time and leap seconds introduce some possibility of error... if that's a problem, go with NSDateComponents.
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setLocale:[NSLocale autoupdatingCurrentLocale]];
NSString *dateString = [formatter stringFromDate:date];
[formatter release];
I'm diving into iOS development and the Objective C language and am building an alarm clock app to become familiar with the SDK and language. I have an NSString object that represents a time, with the range "1:00 am" to "12:59 am". I need to convert this NSString into two NSInteger's that contain the hour value and minute value. As I'm doing this, I'm finding the NSString manipulation that I'm doing to be extremely laborious and it just feels like sloppy code.
Is there a simple way to extract the hour and minute characters from a NSString representation of a time value and store their numerical values in two NSInteger's?
Thanks in advance for all your help! I'm gonna get back to it...
NSScanner* timeScanner=[NSScanner scannerWithString:...the time string...];
int hours,minutes;
[timeScanner scanInt:&hours];
[timeScanner scanString:#":" intoString:nil]; //jump over :
[timeScanner scanInt:&minutes];
NSLog(#"hours:%d minutes:%d",hours,minutes);
Use an NSDateFormatter to convert your string into an NSDate.
Use the [NSCalendar currentCalendar] to extract various date components (like the hour, minute, etc).
In other words:
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"h:m a"];
NSDate *date = [formatter dateFromString:#"12:59 pm"];
[formatter release];
NSDateComponents * components = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
NSLog(#"hour: %d", [components hour]);
NSLog(#"minute: %d", [components minute]);
This is the official way, as I know it. It's not pretty:
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc]init] autorelease];
[dateFormatter setDateFormat:#"h:m a"];
NSDate *date = [dateFormatter dateFromString:#"12:34 am"];
[dateFormatter setDateFormat:#"h"];
NSString *hours = [dateFormatter stringFromDate:date];
[dateFormatter setDateFormat:#"m"];
NSString *minutes = [dateFormatter stringFromDate:date];
BUT the string fiddling way of doing it (look for :, look for space, ...), may give you more headaches on the long term.
NSString *time = #"1:00 am";
NSString *removeam = [time stringByReplacingOccurencesOfString:#" am" withString:#""];
SString *removepm = [removeam stringByReplacingOccurencesOfString:#" pm" withString:#""];
NSArray *timeArray = [removepm componentsSeparatedByString:#":"];
NSInteger *hour = [[timeArray objectAtIndex:0] intValue];
NSInteger *mins = [[timeArray objectAtIndex:1] intValue];
If you're building an alarm clock app, you probably will want to look into the NSDate and NSDateFormatter classes, instead of trying to pull all those strings apart into integer types. Also, your time range is a bit weird (maybe a typo?) - don't you want all 24 hours to be available?
get the time interval and write it as
duration.text = [NSString stringWithFormat:#"%d:%02d", (int)audioPlayer.duration / 60, (int)audioPlayer.duration % 60, nil];