如何设置 NSDate 上的时间?

发布于 2024-12-03 03:20:37 字数 213 浏览 4 评论 0原文

我想用我想要的小时:分钟:秒设置 NSDate 时间 目前我正在使用 NSDate 组件,但它没有给出期望的结果

[comps setHour: -hours];
[comps setMinute:0];
[comps setSecond:0];
NSDate *minDate = [calendar_c dateFromComponents:comps];

I want to set the NSDate time with my desired hours:minutes:seconds
currently im working with NSDate component but it is not giving the desired result

[comps setHour: -hours];
[comps setMinute:0];
[comps setSecond:0];
NSDate *minDate = [calendar_c dateFromComponents:comps];

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

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

发布评论

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

评论(6

野生奥特曼 2024-12-10 03:20:37

这非常适合作为 NSDate 类别。

/** Returns a new NSDate object with the time set to the indicated hour, 
  * minute, and second.
  * @param hour The hour to use in the new date.
  * @param minute The number of minutes to use in the new date.
  * @param second The number of seconds to use in the new date.
  */
-(NSDate *) dateWithHour:(NSInteger)hour 
                  minute:(NSInteger)minute 
                  second:(NSInteger)second 
{
   NSCalendar *calendar = [NSCalendar currentCalendar];
   NSDateComponents *components = [calendar components: NSYearCalendarUnit|
                                                         NSMonthCalendarUnit|
                                                         NSDayCalendarUnit
                                               fromDate:self];
    [components setHour:hour];
    [components setMinute:minute];
    [components setSecond:second];
    NSDate *newDate = [calendar dateFromComponents:components];
    return newDate;
}

对于上述类别,如果您想要更改现有日期的时间,则可以这样做:

NSDate *newDate = [someDate dateWithHour:10 分钟:30 秒:00];

如果但是,您尝试在现有日期中添加或减去小时数,执行此操作的类别方法也很简单:

/** Returns a new date with the given number of hours added or subtracted.
  * @param hours The number of hours to add or subtract from the date.
  */
-(NSDate*)dateByAddingHours:(NSInteger)hours
{
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setHour:hours];

    return [[NSCalendar currentCalendar] 
               dateByAddingComponents:components toDate:self options:0];
}

This works great as an NSDate category.

/** Returns a new NSDate object with the time set to the indicated hour, 
  * minute, and second.
  * @param hour The hour to use in the new date.
  * @param minute The number of minutes to use in the new date.
  * @param second The number of seconds to use in the new date.
  */
-(NSDate *) dateWithHour:(NSInteger)hour 
                  minute:(NSInteger)minute 
                  second:(NSInteger)second 
{
   NSCalendar *calendar = [NSCalendar currentCalendar];
   NSDateComponents *components = [calendar components: NSYearCalendarUnit|
                                                         NSMonthCalendarUnit|
                                                         NSDayCalendarUnit
                                               fromDate:self];
    [components setHour:hour];
    [components setMinute:minute];
    [components setSecond:second];
    NSDate *newDate = [calendar dateFromComponents:components];
    return newDate;
}

With the above category, if you have an existing date you want to change the time on, you do so like this:

NSDate *newDate = [someDate dateWithHour:10 minute:30 second:00];

If, however, you are trying to add or subtract hours from an existing date, a category method to do that is also straightforward:

/** Returns a new date with the given number of hours added or subtracted.
  * @param hours The number of hours to add or subtract from the date.
  */
-(NSDate*)dateByAddingHours:(NSInteger)hours
{
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setHour:hours];

    return [[NSCalendar currentCalendar] 
               dateByAddingComponents:components toDate:self options:0];
}
混浊又暗下来 2024-12-10 03:20:37

你的方法应该可以正常工作。我需要解决此类问题(设置单独的日期组件),并且以下代码按我的预期工作。我的情况:我想创建一个使用当前日期的日期对象,但将时间设置为作为字符串传入的值。

NSString *string = @"7:00";
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSDateFormatter *timeOnlyFormatter = [[NSDateFormatter alloc] init];
[timeOnlyFormatter setLocale:locale];
[timeOnlyFormatter setDateFormat:@"h:mm"];

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

NSDateComponents *comps = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[timeOnlyFormatter dateFromString:string]];
comps.day = todayComps.day;
comps.month = todayComps.month;
comps.year = todayComps.year;
NSDate *date = [calendar dateFromComponents:comps];
[calendar release];
[timeOnlyFormatter release];
[locale release];

需要注意的一件事是,当您判断时间是否准确时,您确实必须注意时区。例如,在我的应用程序中,当您在断点处停止时,您将看到 GMT 时间(因此它看起来与输入时间不同,输入时间是我的当地时间),但是当时间实际显示在屏幕上时应用程序,它正在被格式化以在本地时区中显示。您可能需要考虑这一点,以确定结果是否实际上与您的预期不同。

如果这没有帮助,你能详细说明“没有给出预期的结果”吗?它给出了什么结果?与您的预期相比如何?

Your approach should work fine. I needed a solution for this type problem (setting the individual date components) and the following code works as expected for me. My situation: I wanted to create a date object that used the current date but had the time set to a value that was passed in as a string.

NSString *string = @"7:00";
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSDateFormatter *timeOnlyFormatter = [[NSDateFormatter alloc] init];
[timeOnlyFormatter setLocale:locale];
[timeOnlyFormatter setDateFormat:@"h:mm"];

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

NSDateComponents *comps = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[timeOnlyFormatter dateFromString:string]];
comps.day = todayComps.day;
comps.month = todayComps.month;
comps.year = todayComps.year;
NSDate *date = [calendar dateFromComponents:comps];
[calendar release];
[timeOnlyFormatter release];
[locale release];

One thing to note is that you really have to pay attention to time zones when you are judging whether a time appears to be accurate. For example, in my app, when you stop at a breakpoint, you will see the time in GMT (so it looks different than the input time, which is in my local time), but when the time is actually displayed on screen in the app, it is being formatted to display in the local timezone. You may need to take this into consideration to determine whether the result is actually different from what you would expect.

If this does not help, can you elaborate on "not giving the desired result"? What result is it giving and how does that compare to what you expected?

祁梦 2024-12-10 03:20:37

是 Swift2

extension NSDate {
    func dateWithHour (hour: Int, minute:Int, second:Int) ->NSDate?{

        let calendar = NSCalendar.currentCalendar(),
            components = calendar.components([.Day,.Month,.Year], fromDate: self)
        components.hour = hour;
        components.minute = minute;
        components.second = second;

        return calendar.dateFromComponents(components)
    }
}

is Swift2

extension NSDate {
    func dateWithHour (hour: Int, minute:Int, second:Int) ->NSDate?{

        let calendar = NSCalendar.currentCalendar(),
            components = calendar.components([.Day,.Month,.Year], fromDate: self)
        components.hour = hour;
        components.minute = minute;
        components.second = second;

        return calendar.dateFromComponents(components)
    }
}
国粹 2024-12-10 03:20:37

您可以将 0 设置为小时、分钟和秒。

NSDateFormatter *tFmt = [[NSDateFormatter alloc] init];

tFmt.dateFormat = @"yyyy-MM-dd";

NSString *strNowDate = [NSString stringWithFormat:@"%@ 00:00:00",[tFmt stringFromDate:[NSDate date]]];

NSDate *nowDate = [NSDate dateWithString:strNowDate formatString:@"yyyy-MM-dd HH:mm:ss"];

You can set 0 to hour, min, and second.

NSDateFormatter *tFmt = [[NSDateFormatter alloc] init];

tFmt.dateFormat = @"yyyy-MM-dd";

NSString *strNowDate = [NSString stringWithFormat:@"%@ 00:00:00",[tFmt stringFromDate:[NSDate date]]];

NSDate *nowDate = [NSDate dateWithString:strNowDate formatString:@"yyyy-MM-dd HH:mm:ss"];
提赋 2024-12-10 03:20:37

Swift 5 解决方案(基于 @dattk 答案)适合那些担心弃用警告的人:)

func date(withHour hour: Int, withMinute minute: Int, withSeconds second: Int) -> Date? { 
   let now = Date() 
   let calendar = NSCalendar.current 
   var components = calendar.dateComponents([.day,.month,.year], from: now)   
   components.hour = hour 
   components.minute = minute 
   components.second = second 
   return calendar.date(from: components) 
}

Swift 5 solution (based on @dattk answer) for those who fear Deprecation warnings :)

func date(withHour hour: Int, withMinute minute: Int, withSeconds second: Int) -> Date? { 
   let now = Date() 
   let calendar = NSCalendar.current 
   var components = calendar.dateComponents([.day,.month,.year], from: now)   
   components.hour = hour 
   components.minute = minute 
   components.second = second 
   return calendar.date(from: components) 
}
流殇 2024-12-10 03:20:37
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:[NSDate date]];
comps.hour = 0;
comps.minute = 15;
NSDate *date = [calendar dateFromComponents:comps];

iOS 8

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:[NSDate date]];
comps.hour = 0;
comps.minute = 15;
NSDate *date = [calendar dateFromComponents:comps];

iOS 8

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文