web-dev-qa-db-ja.com

今日の真夜中にNSDateオブジェクトを取得するにはどうすればよいですか?

現在の日の真夜中を表すNSDateオブジェクトを取得する最も効率的な方法は何ですか?

59
markdorison

これを試して:

NSDate *const date = NSDate.date;
NSCalendar *const calendar = NSCalendar.currentCalendar;
NSCalendarUnit const preservedComponents = (NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay);
NSDateComponents *const components = [calendar components:preservedComponents fromDate:date];
NSDate *const normalizedDate = [calendar dateFromComponents:components];
65

iOS 8の新しいAPI

iOS 8には、NSCalendarにstartOfDayForDateと呼ばれる新しいメソッドが含まれています。

let startOfToday = NSCalendar.currentCalendar().startOfDayForDate(NSDate())

Appleの説明:

このAPIは、指定された日付の最初の瞬間の日付を返します。たとえば、「今日」の開始を希望する場合は、[NSDate date]を渡します。深夜が2回あった場合は、最初の夜を返します。存在しなかった場合、存在した最初の瞬間を返します。

タイムゾーンに関する更新:

StartOfDayForDateはNSCalendarのメソッドであるため、NSCalendarのタイムゾーンを使用します。ですから、今日がロサンゼルスで始まったニューヨークの時間を知りたい場合、これを行うことができます:

let losAngelesCalendar = NSCalendar.currentCalendar().copy() as! NSCalendar
losAngelesCalendar.timeZone = NSTimeZone(name: "America/Los_Angeles")!

let dateTodayBeganInLosAngeles = losAngelesCalendar.startOfDayForDate(NSDate())
dateTodayBeganInLosAngeles.timeIntervalSince1970

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .ShortStyle
dateFormatter.timeZone = NSTimeZone(name: "America/New_York")!
let timeInNewYorkWhenTodayBeganInLosAngeles = dateFormatter.stringFromDate(dateTodayBeganInLosAngeles)
print(timeInNewYorkWhenTodayBeganInLosAngeles) // prints "Jul 29, 2015, 3:00 AM"
97
Richard Venable
NSCalendar *cal = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; 
[cal setTimeZone:[NSTimeZone systemTimeZone]];  

 NSDateComponents * comp = [cal components:( NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]]; 

 [comp setMinute:0]; 
 [comp setHour:0];
 [comp setSecond:0]; 

 NSDate *startOfToday = [cal dateFromComponents:comp]; 

真夜中を23:59とする場合、コンポーネントの時間を23、分を59に設定します。

12
aslisabanci

迅速:

let cal = NSCalendar.currentCalendar()

//tip:NSCalendarUnit can be omitted, but with the presence of it, you can take advantage of Xcode's auto-completion
var comps = cal.components(NSCalendarUnit.YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit | .HourCalendarUnit | .MinuteCalendarUnit | .SecondCalendarUnit, fromDate: NSDate()) 
comps.hour = 0
comps.minute = 0
comps.second = 0

let midnightOfToday = cal.dateFromComponents(comps)!

Swift 2.2:

let cal = NSCalendar.currentCalendar()

let comps = cal.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: NSDate())
comps.hour = 0
comps.minute = 0
comps.second = 0

let midnightOfToday = cal.dateFromComponents(comps)!

Objective-C:

NSCalendar *cal = [NSCalendar currentCalendar]; 

NSDateComponents *comps = [cal components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:[NSDate date]];    
[comps setHour:0]; 
[comps setMinute:0]; 
[comps setSecond:0];

NSDate *midnightOfToday = [cal dateFromComponents:comps];
8
fujianjin6471

次のメソッドを使用して、NSDateの真夜中の値を取得できます。

- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate
{
    // Use the user's current calendar and time zone
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    [calendar setTimeZone:timeZone];

    // Selectively convert the date components (year, month, day) of the input date
    NSDateComponents *dateComps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:inputDate];

    // Set the time components manually
    [dateComps setHour:0];
    [dateComps setMinute:0];
    [dateComps setSecond:0];

    // Convert back       
    NSDate *beginningOfDay = [calendar dateFromComponents:dateComps];
    return beginningOfDay;
}

Thkisはここから取得されます website

8
Alex Stanciu

iOS8からは、startDayForDateを使用できます。

それで、今日の始まりを得るために(Objective -C):

NSDate * midnight;
 midnight = [[NSCalendar currentCalendar] startOfDayForDate: [NSDate date]];
3
joan
NSDate *now = [NSDate date];
NSDate *beginningOfToday = nil;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&beginningOfToday interval:NULL forDate:now];
1
Qiulang

これを試して:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *components = [gregorian components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:now];
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss.SSS"];
NSLog(@"%@",[df stringFromDate:[gregorian dateFromComponents:components]]);
1
Dyorgio
    let calendar = NSCalendar.currentCalendar()
    let unitFlags: NSCalendarUnit = [.Year, .Month, .Day, .Minute, .Second]
    let components = calendar.components(unitFlags , fromDate: NSDate())

    components.hour = 0
    components.minute = 0
    components.second = 0

    //Gives Midnight time of today
    let midnightOfToday = calendar.dateFromComponents(components)!
0
Mohammad Yaqoob

NSCalendar 's dateBySettingHour:minute:second:ofDate:options:

したがって、次のように簡単になります。

NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];

NSDate *midnight = [calendar dateBySettingHour:0 minute:0 second:0 ofDate:[NSDate date] options:0];
0
Thecafremo