如何设置现有的 NSDate 时间?

发布于 2024-10-24 22:37:12 字数 447 浏览 1 评论 0原文

如何设置现有 NSDate 的时间?

也就是说,我有一个日期(例如当前日期/时间),但随后想将其设置为特定时间(例如上午 11.23 点)。在目标 C 中执行此操作的最快方法是什么?

我正在查看 NSCalendar 并查看诸如 dateByAddingComponents:toDate:options:dateFromComponents: 之类的方法,但这些似乎并不非常符合我在这里所需要的。例如:

  1. dateFromComponents: - 我必须计算出所有组件才能使其工作,这似乎有点矫枉过正
  2. dateByAddingComponents:toDate:options: - 我不想添加就我而言,而是“设定”时间。

how do I set an existing NSDate's time?

That is I have a date (say current date/time), but then want to set this to a specific time (e.g. 11.23am) say. What is the quickest way to do this in objective C?

I'm looking at NSCalendar and see methods such as dateByAddingComponents:toDate:options:, and dateFromComponents:, but these don't seem to quite hit the mark for what I need here. For example:

  1. dateFromComponents: - I would have to work out all components for this to work which seems like overkill
  2. dateByAddingComponents:toDate:options: - I don't want to ADD in my case but rather "set" the time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

躲猫猫 2024-10-31 22:37:12
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];

NSDate *newDate = [gregorian dateFromComponents: components];

我使用 NSUIntegerMax 而不是特定的 OR 组合位掩码,因为它更容易,但如果您想指定接收哪些数据组件,请成为我的客人。

NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];

NSDate *newDate = [gregorian dateFromComponents: components];

I use NSUIntegerMax instead of specific OR-combined bit masks because it's easier, but if you want to specify which data components to receive, be my guest.

漆黑的白昼 2024-10-31 22:37:12

iOS 7 注意:我将其放在其中几个问题中,因为 NSUIntegerMax 的使用似乎不再适用于 iOS7,并且使用它导致我追了大约 3 个小时。我刚刚发现,当我使用 NSUIntegerMax 时,NSDateComponents 忽略设置的年份。例如,这不会改变年份:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:NSUIntegerMax fromDate:date];
[comps setYear:year];
return [gregorian dateFromComponents:comps];

而这会改变年份:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger timeComps = (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSTimeZoneCalendarUnit);
NSDateComponents *comps = [gregorian components:timeComps fromDate:date];
[comps setYear:year];
return [gregorian dateFromComponents:comps];

这可能是 iOS7 的错误,或者可能是使用 NSUIntegerMax 工作只是侥幸,不再有效。我将提交错误报告并得到明确的答案。

无论如何,如果您想避免意外的后果,请指定所有组件,否则您可能会陷入困境!

iOS 7 Note: I'm putting this in a few of these questions because use of NSUIntegerMax no longer seems to work on iOS7, and using it caused me to chase my tail for about 3 hours. I just discovered that when I use NSUIntegerMax, NSDateComponentsignores set year. So for example this DOES NOT change the year:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:NSUIntegerMax fromDate:date];
[comps setYear:year];
return [gregorian dateFromComponents:comps];

Whereas this DOES:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger timeComps = (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSTimeZoneCalendarUnit);
NSDateComponents *comps = [gregorian components:timeComps fromDate:date];
[comps setYear:year];
return [gregorian dateFromComponents:comps];

It may be an iOS7 bug or it may be that using NSUIntegerMax working was a fluke which no longer works. I will file a bug report and get a definitive answer.

Regardless, if you want to avoid unexpected consequences specify ALL the components else you might be chasing your tail!

洋洋洒洒 2024-10-31 22:37:12

Swift 2.0 版本如何将给定日期设置为上午 8 点

extension NSDate {

func setTo8AM() -> NSDate {
    let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let components = calendar.components(([.Day, .Month, .Year]), fromDate: self)
    components.hour = 8
    return calendar.dateFromComponents(components)!
}

}

Swift 2.0 version of how you'd set a given date to 8am

extension NSDate {

func setTo8AM() -> NSDate {
    let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let components = calendar.components(([.Day, .Month, .Year]), fromDate: self)
    components.hour = 8
    return calendar.dateFromComponents(components)!
}

}
天冷不及心凉 2024-10-31 22:37:12

应用此设置将时间从另一个日期设置为现有日期

NSDate *today = [NSDate date]; // from which i need only "Year" "Month" "Date"

NSCalendar *calendar = [NSCalendar currentCalendar]
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) fromDate:today];

NSDate *timeDate = datePicker.date; // from which i need only "Hours" "Minutes" and "Seconds"

NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:timeDate];

            [dateComponents setHour:[timeComponents hour]];
            [dateComponents setMinute:[timeComponents minute]];
            [dateComponents setSecond:[timeComponents second]];

NSDate *newDate = [calendar dateFromComponents:dateComponents]; // New Date with My "Year" "Month" "Date" "Hours" "Minutes" and "Seconds" 

            NSLog(@"New Date: %@",newDate);

Apply this to set the Time from an another date to an existing Date

NSDate *today = [NSDate date]; // from which i need only "Year" "Month" "Date"

NSCalendar *calendar = [NSCalendar currentCalendar]
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) fromDate:today];

NSDate *timeDate = datePicker.date; // from which i need only "Hours" "Minutes" and "Seconds"

NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:timeDate];

            [dateComponents setHour:[timeComponents hour]];
            [dateComponents setMinute:[timeComponents minute]];
            [dateComponents setSecond:[timeComponents second]];

NSDate *newDate = [calendar dateFromComponents:dateComponents]; // New Date with My "Year" "Month" "Date" "Hours" "Minutes" and "Seconds" 

            NSLog(@"New Date: %@",newDate);
一曲琵琶半遮面シ 2024-10-31 22:37:12

这是一个更通用的 Swift (v2.1.1) 扩展,它基于 Andrew Schreiber 的有用答案。

extension NSDate {
    func dateWithTime(hour: Int, minute: Int, second: Int) -> NSDate? {
        let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let components = calendar.components(([.Day, .Month, .Year]), fromDate: self)
        components.hour = hour
        components.minute = minute
        components.second = second
        let newDate = calendar.dateFromComponents(components)
        return newDate
    }
}

Here's a more generic Swift (v2.1.1) extension that builds on Andrew Schreiber's helpful answer.

extension NSDate {
    func dateWithTime(hour: Int, minute: Int, second: Int) -> NSDate? {
        let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let components = calendar.components(([.Day, .Month, .Year]), fromDate: self)
        components.hour = hour
        components.minute = minute
        components.second = second
        let newDate = calendar.dateFromComponents(components)
        return newDate
    }
}
氛圍 2024-10-31 22:37:12

一个简单的例子。出于我的目的,我想获取明天中午 12 点左右的日期。

var tomorrow:NSDate = NSDate().dateByAddingTimeInterval(60*60*24); //60seconds*60minutes*12hours
var gregorian:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!;
var unit : NSCalendarUnit = (NSCalendarUnit.YearCalendarUnit|NSCalendarUnit.MonthCalendarUnit|NSCalendarUnit.DayCalendarUnit|NSCalendarUnit.HourCalendarUnit|NSCalendarUnit.MinuteCalendarUnit);
var comps:NSDateComponents = gregorian.components(unit, fromDate: tomorrow);
comps.setValue(12, forComponent: NSCalendarUnit.HourCalendarUnit);
comps.setValue(0, forComponent: NSCalendarUnit.MinuteCalendarUnit);
var noon_tomorrow : NSDate = gregorian.dateFromComponents(comps)!;

A swift example. For my purposes, I wanted to get the date for around 12 noon tomorrow.

var tomorrow:NSDate = NSDate().dateByAddingTimeInterval(60*60*24); //60seconds*60minutes*12hours
var gregorian:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!;
var unit : NSCalendarUnit = (NSCalendarUnit.YearCalendarUnit|NSCalendarUnit.MonthCalendarUnit|NSCalendarUnit.DayCalendarUnit|NSCalendarUnit.HourCalendarUnit|NSCalendarUnit.MinuteCalendarUnit);
var comps:NSDateComponents = gregorian.components(unit, fromDate: tomorrow);
comps.setValue(12, forComponent: NSCalendarUnit.HourCalendarUnit);
comps.setValue(0, forComponent: NSCalendarUnit.MinuteCalendarUnit);
var noon_tomorrow : NSDate = gregorian.dateFromComponents(comps)!;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文