我有 NSString *localized_Date = minutesSinceMidnightToLocalizedTime (时间单位)
我在 4:30 am, 10.00pm 得到这个字符串
如何将此字符串转换为 NSDate?请告诉我。
我有 NSString *localized_Date = minutesSinceMidnightToLocalizedTime (时间单位)
我在 4:30 am, 10.00pm 得到这个字符串
如何将此字符串转换为 NSDate?请告诉我。
NSDateFormatter 是你的朋友,使用适合你的日期/时间的格式
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:[NSString stringWithFormat:@"dd MMM yyyy HH:mm"]];
NSDate *_date = [df dateFromString:string];
约翰
试试这个代码:
NSString *dateString = @"4:30 am";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
NSDate *date = [dateFormatter dateFromString:dateString];
希望这会帮助你。
我知道这是一个有点长的代码,但我想让它尽可能可读。此代码使用 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];