Question

I have NSString *localized_Date = minutesSinceMidnightToLocalizedTime (time units)

I get this string as 4:30 am, 10.00pm

how do I convert this string to NSDate? PLease let me know.

Was it helpful?

Solution

I know it's a bit long code, but I wanted to make it as readable as possible. This code uses minutesSinceMidnight instead of the localized string.

NSDate *currentDate = [NSDate date];
NSDateComponents *currentDateComponents = [calendar components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:currentDate];
NSDateComponents *currentDateToMidnight = [[NSDateComponents alloc] init];
[currentDateToMidnight setHour:-[currentDateComponents hour]];
[currentDateToMidnight setMinute:-[currentDateComponents minute]];
[currentDateToMidnight setSecond:-[currentDateComponents second]];
NSDate *midnight = [calendar dateByAddingComponents:currentDateToMidnight toDate:currentDate options:0];
NSDateComponents *midnightToDesiredDate = [[NSDateComponents alloc] init];
[midnightToDesiredDate setMinute:minutesSinceMidnight];
NSDate *desiredDate = [calendar dateByAddingComponents:midnightToDesiredDate toDate:midnight options:0];

OTHER TIPS

NSDateFormatter is your friend, use the formats that suits your date/time

NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease]; 
[df setDateFormat:[NSString stringWithFormat:@"dd MMM yyyy HH:mm"]]; 
NSDate *_date = [df dateFromString:string]; 

Johan

Try this code:

NSString *dateString = @"4:30 am";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"hh:mm a"];

NSDate *date = [dateFormatter dateFromString:dateString];

Hope this will help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top