我想把时间分割成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);
但是我能够打印前十分钟的分裂…谁能告诉我怎么循环?
其他两个答案都是错误的,因为它们没有考虑到夏令时。要做到这一点,必须使用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];
}
在这段代码中,我实际上并没有通过NSDateFormatter
运行NSDate
对象,因为这应该发生在不同的级别。这些代码都是关于底层数据(模型)的,而NSDateFormatter
通常在用户可见级别(视图)操作。另外,使用原始数据对象通常比使用格式化字符串更有用。
试试下面的代码
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);
}
试试
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];
}