创建具有特定时间的 NSDate [英] Create NSDate with a specific time

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

问题描述

我有以下问题.我需要从特定时间创建一个 NSDate 对象.在给定的时区(有时是 CST、EST 等),今天的时间是下午 6 点.不是每天下午 6 点,而是该特定时区的今天下午 6 点.

I have the following problem. I need to create an NSDate object from a specific time. The time is 6 pm for today in a given timezone (sometimes CST, EST etc). Not 6 pm for every day, but 6pm for today in that particular timezone.

我正在考虑使用 NSCalendar 对象来创建特定的日期/时间,但问题是它需要日、月和年.那么当我没有正确的日期时如何设置这些值.示例:

I was thinking of using the NSCalendar object to create the specific date/time but the problem is that it needs a day, month and year. So how do I set these values when I don't have the correct date for it. Example :

今天是 2014 年 1 月 28 日,美国中部时间 11:09.现在,如果我需要创建一个 NSCalendar 对象,我将需要日、月和年.我不能使用 NSDate 对象的日、月和年计算,因为它会导致边缘情况出现问题.

Today is 28th January 2014, 11:09 in CST. Now if I need to create a NSCalendar object I would need the day, month and year. I cannot use the NSDate object's day, month and year calculations as it will lead to problems with edge cases.

谁能指出我正确的方向?

Can anyone point me in the right direction?

推荐答案

您关心的似乎是边缘情况,这向我表明,您实际上是在寻找下一个下午 6 点",而不是今天下午 6 点",即如果时间已经过了 6pm 你想要明天 6pm 吗?

Your concern seems to be about edge cases, this suggests to me that rather than "6pm today" you are actually looking for the "next 6pm", i.e. if the time is past 6pm you want 6pm tomorrow?

也许以下内容会有所帮助,无论我的猜测是否正确:

Maybe the following will help, whether my guess is correct or not:

  1. 获取当前日期 &时间 - NSDate
  2. 获取当前日历 - NSCalendar
  3. 将日历的时区设置为您想要的时区
  4. 使用日历将日期转换为组件 - NSDateComponents - 仅提取年、月、日、小时和小时的组件时区.您现在可以将目标时区中的当前时间组件向下舍入到最接近的小时.
  5. 使用日历从提取的时间组件中创建一个 NSDate.您现在将四舍五入的停机时间设为 NSDate.
  6. 使用您的组件计算要添加的小时数以将时间提前到下一个下午 6 点.
  7. 将小时数转换为秒数以生成 NSTimeInterval 值,将该间隔添加到您的舍入日期.NSDate 将根据需要处理提前日期、更改月份等的边缘情况.
  1. Get the current date & time - NSDate
  2. Get the current calendar - NSCalendar
  3. Set the time zone of the calendar to your desired time zone
  4. Using the calendar convert the date to components - NSDateComponents - only extracting the components for year, month, day, hour & time zone. You now have the current time components in the target time zone rounded down to the nearest hour.
  5. Create an NSDate from your extracted time components using your calendar. You now have your rounded down time as an NSDate.
  6. Using your components calculate the number of hours to add to advance the time to the next 6pm.
  7. Convert the number of hours to seconds to produce an NSTimeInterval value, add that interval to your rounded down date. NSDate will take care of the edge cases of advancing the date, changing the month, etc. as needed.

HTH

这篇关于创建具有特定时间的 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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