我想以30分钟的间隔分割时间,所以我可以得到这样的时间:
12:00 AM 12:10 AM 12:20 AM ..........直到晚上11:50。
我正在尝试这样的事情:
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"hh:mm a"];
NSDate* fromTime = [timeFormat dateFromString:startTime];
NSDate* toTime = [timeFormat dateFromString:endTime];
NSLog(@"Start time %@",fromTime);
NSLog(@"End time %@",toTime);
NSDate *dateByAddingThirtyMinute;
dateByAddingThirtyMinute = [fromTime dateByAddingTimeInterval:1800];
NSString *formattedDateString;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
formattedDateString = [dateFormatter stringFromDate:dateByAddingThirtyMinute];
NSLog(@"Time after 10 min %@",formattedDateString);
但我可以打印前十分钟分裂...... 任何人都可以帮助我如何循环它...
答案 0 :(得分:2)
其他两个答案都是错误的,因为它们没有考虑夏令时。为此,您必须使用NSDateComponents
和NSCalendar
:
NSDate *startDate = ...;
NSDate *endDate = ...;
NSDateComponents *diff = [[NSDateComponents alloc] init];
[diff setMinute:0];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *tmp = startDate;
NSMutableArray *dates = [NSMutableArray arrayWithObject:tmp];
while ([tmp laterDate:endDate] == endDate) {
[diff setMinute:[diff minute] + 10];
tmp = [cal dateByAddingComponents:diff toDate:startDate options:0];
[dates addObject:tmp];
}
在这段代码中,我实际上并没有通过NSDate
运行NSDateFormatter
个对象,因为这应该发生在不同的级别。此代码全部与基础数据(模型)有关,NSDateFormatter
通常在用户可见级别(视图)运行。另外,拥有原始数据对象通常比格式化字符串更有用。
答案 1 :(得分:0)
试试这个
int numberOfIntervals = [toDate timeIntervalSinceDate:fromDate]/(10*60);
for (int i = 0; i < numberOfIntervals; i++) {
NSDate *theDate = [date dateByAddingTimeInterval:i * 60 * 10];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
NSString *formattedDateString = [dateFormatter stringFromDate:dateByAddingThirtyMinute];
NSLog(@"Time after 10 min %@",formattedDateString);
[dateFormatter release];
}
答案 2 :(得分:0)
尝试使用以下代码
NSString *startTime = @"12:00 AM";
NSString *endTime = @"11:40 AM";
NSDateFormatter *timeFormat = [[[NSDateFormatter alloc] init] autorelease];
[timeFormat setDateFormat:@"hh:mm a"];
NSDate* fromTime = [timeFormat dateFromString:startTime];
NSDate* toTime = [timeFormat dateFromString:endTime];
NSDate *dateByAddingThirtyMinute ;
NSTimeInterval timeinterval = [toTime timeIntervalSinceDate:fromTime];
NSLog(@"time Int %f",timeinterval/3600);
float numberOfIntervals = timeinterval/3600;
NSLog(@"Start time %f",numberOfIntervals);
for(int iCount = 0;iCount<numberOfIntervals*6 ;iCount ++)
{
dateByAddingThirtyMinute = [fromTime dateByAddingTimeInterval:600];
fromTime = dateByAddingThirtyMinute;
NSString *formattedDateString;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"hh:mm a"];
formattedDateString = [dateFormatter stringFromDate:dateByAddingThirtyMinute];
NSLog(@"Time after 10 min %@",formattedDateString);
}