将浮点数转换为 NSDate

发布于 2024-07-19 05:00:33 字数 652 浏览 4 评论 0原文

我想将浮点数转换为 NSDate

我使用以下方法将 NSDate 转换为浮点数:

// Turn the date into Integers 
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;  
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:nsdate_wakeTime];  
NSInteger hour = [dateComponents hour];  
NSInteger min = [dateComponents minute];  

//Convert the time in 24:60 to x.x format.
float myTime = hour + min/60; 

在对 mytime 变量执行一些数学操作后,我得到了相同浮点数格式的许多其他时间。

如何将 float 转换为 NSDate?

谢谢!

I want to convert a float to a NSDate

I converted a NSDate into a float using this:

// Turn the date into Integers 
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;  
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:nsdate_wakeTime];  
NSInteger hour = [dateComponents hour];  
NSInteger min = [dateComponents minute];  

//Convert the time in 24:60 to x.x format.
float myTime = hour + min/60; 

after some math stuff I do on the mytime variable i get a bunch of other times in the same float format.

How do I turn a float into a NSDate?

Thanks!

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

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

发布评论

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

评论(1

超可爱的懒熊 2024-07-26 05:00:33

如果将计算出的时间转换为秒(例如 mytime * 60),则可以使用 dateWithTimeIntervalSinceReferenceDate: 来返回到 NSDate。 从您正在进行的数学计算来看,此处引用的日期似乎是相关日期的 00:00。 正如杰森提到的,可能有更好的方法来完成您想要完成的任务。

另外,如果您确实想要分钟数,则需要将“myTime”计算更改为除以 60.0; 您的示例代码将小于 60 的整数值除以整数值 60,该值始终为 0。

If you convert the time you've computed to seconds (so, mytime * 60), then you can use dateWithTimeIntervalSinceReferenceDate: to get back to an NSDate. From the math you are doing, it looks like the referenced date here would be 00:00 for the day in question. As Jason mentioned though, there's probably a better way to do what you are trying to accomplish.

Also, you need to change your "myTime" computation to dividing by 60.0 if you actually want the minutes; your sample code is dividing an integer value less than 60 by the integer value 60, which will always be 0.

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