Reputation: 1818
When I try to get values for date and time from text fields I got wrong value on console. Date and time are two text fields
NSString *datestring = self.date.text;
NSString *timestring = self.time.text;
NSString *combined = [NSString stringWithFormat:@"%@ %@",datestring,timestring];
NSLog(@"%@",combined);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM dd yyyy HH:mm:ss"];
NSDate *dates = [dateFormat dateFromString:combined];
NSLog(@"%@",dates);
Upvotes: 0
Views: 203
Reputation: 112857
Do not rely on the NSDate
description
method to give you the date you want, it is really just for debugging. Instead use NSDateFormatter
method stringFromDate:
.
NSString *combinedDateString = @"may 2 2000 02:00 AM";
NSLog(@"combinedDateString: %@", combinedDateString);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM dd yyyy hh:mm aa"];
NSDate *date = [dateFormat dateFromString:combinedDateString];
NSString *recoveredDateString = [dateFormat stringFromDate:date];
NSLog(@"recoveredDateString: %@", recoveredDateString);
NSLog output:
combinedDateString: may 2 2000 02:00 AM
recoveredDateString: May 02 2000 02:00 AM
Choose a different display format as desired.
Note: "HH" is for 24 hour time, "hh" is for 12 hour time.
See ICU Formatting Dates and Times for date formatting.
Upvotes: 1
Reputation: 27
You have wrong formatter, it must be:
[dateFormat setDateFormat:@"MMMM dd yyyy hh:mm aa"];
You have already open a subject: I didn't get correct time when using time formatter
Upvotes: 0