如何设置现有NSDate的时间? [英] how do I set an existing NSDate's time?

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

问题描述

如何设置现有NSDate的时间?

那是我有一个日期(例如当前日期/时间),但是想将其设置为特定时间(例如上午11.23).在目标C中最快的方法是什么?

That is I have a date (say current date/time), but then want to set this to a specific time (e.g. 11.23am) say. What is the quickest way to do this in objective C?

我正在查看NSCalendar并看到诸如dateByAddingComponents:toDate:options:dateFromComponents:之类的方法,但是这些方法似乎并没有达到我所需要的标准.例如:

I'm looking at NSCalendar and see methods such as dateByAddingComponents:toDate:options:, and dateFromComponents:, but these don't seem to quite hit the mark for what I need here. For example:

  1. dateFromComponents:-我必须弄清楚所有组件,才能正常工作
  2. dateByAddingComponents:toDate:options:-我不想添加我的情况,而是设置"时间.
  1. dateFromComponents: - I would have to work out all components for this to work which seems like overkill
  2. dateByAddingComponents:toDate:options: - I don't want to ADD in my case but rather "set" the time.

推荐答案

NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];

NSDate *newDate = [gregorian dateFromComponents: components];

我使用NSUIntegerMax而不是特定的OR组合位掩码,因为它更容易,但是如果您要指定接收哪些数据组件,请成为我的客人.

I use NSUIntegerMax instead of specific OR-combined bit masks because it's easier, but if you want to specify which data components to receive, be my guest.

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

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