我有NSString * localized_Date = minutesSinceMidnightToLocalizedTime(时间单位)
我收到这个字符串是凌晨4:30,晚上10点
如何将此字符串转换为NSDate? 请告诉我。
答案 0 :(得分:0)
NSDateFormatter是您的朋友,请使用适合您日期/时间的格式
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:[NSString stringWithFormat:@"dd MMM yyyy HH:mm"]];
NSDate *_date = [df dateFromString:string];
约翰
答案 1 :(得分:0)
试试这段代码:
NSString *dateString = @"4:30 am";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
NSDate *date = [dateFormatter dateFromString:dateString];
希望这会对你有所帮助。
答案 2 :(得分:0)
我知道它有点长代码,但我希望尽可能让它变得可读。 此代码使用minutesSinceMidnight而不是本地化字符串。
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];