【问题标题】:Convert minute of day into NSDate?将一天中的分钟转换为 NSDate?
【发布时间】:2018-01-04 19:06:30
【问题描述】:

下午好,我正在开发一个应用程序,它使用的 API 提供一天中的分钟而不是直接的日期(例如,“分钟”:23)。我如何将其转换为 12:23AM 或 00:23 的日期对象(两者都无关紧要)。我尝试使用 TimeInterval 但无法弄清楚。

【问题讨论】:

  • 您可以使用(NS)DateComponents
  • NSDates 仅代表时间的精确瞬间,而不是像“第 23 分钟”这样的抽象事物。正如@Larme 提到的,NSDateComponents 可以用来代替它。
  • 你的实际目标是什么?您是否希望将诸如 690 之类的数字在上午 11:30 转换为今天的日期作为 Date 实例。或者您是否希望将诸如 690 之类的数字转换为诸如“11:30”之类的字符串? Edit你的问题要清楚地解释你真正想要什么。

标签: swift date nsdate


【解决方案1】:

如果您的日期始终引用当前日期,您可以执行以下操作:

//minutes from API, hardcoded for example
let minute = 123

let calendar = Calendar.current
//Get the current year, month, and day as individual date components
var components = calendar.dateComponents([.calendar, .year, .month, .day], from: Date())

//Set minutes
components.minute = minute

//Get the full date.  As of today, resolves to "Jan 4, 2018 at 2:03 AM"
let date = components.date

【讨论】:

  • @LeoDabus 你是对的——我没有意识到这一点。我会编辑。
猜你喜欢
  • 2014-12-01
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多