Search code examples
objective-cnsdatedate-conversionlocalized

how to convert localized Date String to NSDate


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.


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];