gpt4 book ai didi

iphone - 将 uidatepicker 格式化为另一个 nsdate

转载 作者:行者123 更新时间:2023-11-29 04:43:35 25 4
gpt4 key购买 nike

我有一个 UIDatePicker,我使用它获取日期:

   NSDate *pickerDate = [datePickerView date];

我想根据 pickerDate 中的星期几和时间 (HH:mm:ss) 创建一个 future 的日期。这是我正在使用的代码,但它生成的日期是错误的:

更新代码

        //format the uidatepicker
NSDate *dateSet = pickerDate;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone localTimeZone]];
[df setDateFormat:@"EEEE HH:mm:ss"];
NSString *dateSetString = [df stringFromDate:dateSet];

NSLog(@"repeatDateString %@",dateSetString);//prints "Tuesday 12:12:43"

//create a new nsdate using the new format
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setTimeZone:[NSTimeZone localTimeZone]];
[dateFormat2 setDateFormat: @"EEEE HH:mm:ss"];

NSDate *newDate = [[NSDate alloc] init];
newDate = [dateFormat2 dateFromString:dateSetString];

NSLog(@"new Date %@",newDate);//prints "1970-01-06 04:42:43 +0000"

最佳答案

问题是您的日期字符串不包含选择器中的所有信息,并且不包含足够的信息来重新创建日期。它缺少日、月和年,因此当您重新创建它时,它会假定您希望从 iOS 的 NSDate 日历系统的开头开始。

您要么需要存储从选择器收到的NSDate(最好),要么需要使用包含足够信息的日期格式来创建特定的日期和时间。

编辑
根据您的评论,您只想使用 datePicker 中的工作日和时间,并使用这些值确定 future 的下一个日期。下面是实现这一点的代码:

NSCalendar          *cal            = [NSCalendar currentCalendar];

NSDate *pickerDate = self.datePickerView.date;
NSDateComponents *pickerComps = [cal components: NSWeekdayCalendarUnit |
NSHourCalendarUnit |
NSMinuteCalendarUnit |
NSSecondCalendarUnit
fromDate:pickerDate];

NSDate *currentDate = [NSDate date];
NSDateComponents *currentComps = [cal components: NSYearCalendarUnit |
NSMonthCalendarUnit |
NSWeekdayCalendarUnit |
NSDayCalendarUnit |
NSHourCalendarUnit |
NSMinuteCalendarUnit |
NSSecondCalendarUnit
fromDate:currentDate];

// Start with the current date and add/subtract the number of days needed to make it the same day of the week
NSDateComponents *newComps = [currentComps copy];
NSUInteger weekdayDiff = pickerComps.weekday - currentComps.weekday;
newComps.day = newComps.day + weekdayDiff;
// If needed, add 7 days in order to move this date into the future
if (newComps.day < currentComps.day) {
newComps.day = newComps.day + 7;
}

NSDate *newDate = [cal dateFromComponents:newComps];
if ([newDate compare:currentDate] == NSOrderedAscending) {
// This is true when the weekday started out the same but the time of day is earlier in the picker.
// Add 7 days
newComps.day = newComps.day + 7;
newDate = [cal dateFromComponents:newComps];
}

NSLog(@"%@", newDate);

关于iphone - 将 uidatepicker 格式化为另一个 nsdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9986647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com