如何在NSDate上设置时间? [英] How to set time on NSDate?

查看:128
本文介绍了如何在NSDate上设置时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将NSDate时间设置为所需的小时:分钟:秒 目前无法使用NSDate组件,但无法获得预期的结果

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];

推荐答案

您的方法应该可以正常工作.我需要针对此类型问题的解决方案(设置各个日期组件),并且以下代码对我来说工作正常.我的情况:我想创建一个日期对象,该对象使用当前日期,但将时间设置为以字符串形式传递的值.

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];

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

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?

这篇关于如何在NSDate上设置时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆