使用特定时间初始化NSDate对象

时间:2011-01-25 19:46:11

标签: iphone nsdate

time格式为string,例如2:00。我想将其初始化为NSDate,并显示date。 我试着做了

   NSDateComponents *comps = [[NSDateComponents alloc] init];
   [comps setHour:2];

我无法将其与日期对象进行比较。请帮忙

5 个答案:

答案 0 :(得分:32)

尝试

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:6];
[comps setMonth:5];
[comps setYear:2004];

NSCalendar *gregorian = [[NSCalendar alloc]
    initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];

您应该可以在此之后与日期进行比较。

也许你的意思是。我认为将使用今天的日期进行设置,然后您可以从中创建NSDateComponents并设置时间值。

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
                    [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
[weekdayComponents setHour:12];
[weekdayComponents setMinute:10];
[weekdayComponents setSeconds:30];

答案 1 :(得分:3)

要初始化当前日期为2的NSDate,您必须将NSDate与组件年,月和日分开,例如

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian
                                       components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                       fromDate:today];

将小时数设为2

weekdayComponents.hour = 2;

然后通过这些组件创建一个新的NSDate

NSDate *todayAt2 = [gregorian dateFromComponents:weekdayComponents];

答案 2 :(得分:2)

您需要使用NSCalendar对象将NSDateComponents转换为NSDate。请参阅Creating a Date from Components上的Apple文档。

答案 3 :(得分:1)

  func initializeDateWithTime(date:NSDate,hrs:Int,minutes:Int) -> NSDate{
    let today = date
     let gregorian:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
     let dateComponents = gregorian.components([.Year, .Month, .Day], fromDate: today)

     dateComponents.hour = hrs;
     dateComponents.minute = minute;


     let todayAtX = gregorian.dateFromComponents(dateComponents)
     return todayAtX!
}

答案 4 :(得分:0)

只是汇集了一些Objective C答案,我(现在)有这个辅助函数:

$computers = get-Content c:\computers.txt
foreach ($computer in $computers){
if(!(Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{write-host "cannot reach $computer" -f red}

else {& \\$computer\C$\Windows\System32\cleanmgr.exe /sagerun:1}}