ios 更改 NSDate 对象的年月日
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17084908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change year, month and day of NSDate object
提问by revolutionkpi
in my iPhone application I have a start date of event, for exemple: 2013-05-17 15:00:12 +0000. My question is, how can I change 2013-05-17 with today date, but leave time the same?
在我的 iPhone 应用程序中,我有一个事件的开始日期,例如:2013-05-17 15:00:12 +0000。我的问题是,如何将 2013-05-17 更改为今天的日期,但保留时间不变?
回答by CaptainRedmuff
You need to gather the date components and amend the required properties.
您需要收集日期组件并修改所需的属性。
//gather current calendar
NSCalendar *calendar = [NSCalendar currentCalendar];
//gather date components from date
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:[NSDate date]];
//set date components
[dateComponents setDay:17];
[dateComponents setMonth:5];
[dateComponents setYear:2013];
//save date relative from date
NSDate *date = [calendar dateFromComponents:dateComponents];
Either that, or you could add the number of seconds in 1 day to increment the value:
或者,您可以在 1 天内添加秒数以增加值:
NSDate *date = [NSDate dateWithTimeInterval:((60 * 60) * 24) sinceDate:[NSDate date]];
回答by ramchandra n
Swift 3 & IOS 10.2
斯威夫特 3 和 IOS 10.2
let calendar = Calendar.current
var dateComponents: DateComponents? = calendar.dateComponents([.hour, .minute, .second], from: Date())
dateComponents?.day = 17
dateComponents?.month = 5
dateComponents?.year = 2013
let date: Date? = calendar.date(from: dateComponents!)
print(date!)
Swift 3 & IOS 10.2
斯威夫特 3 和 IOS 10.2
回答by onmyway133
Read more on my blog https://github.com/onmyway133/blog/issues/54
在我的博客上阅读更多https://github.com/onmyway133/blog/issues/54
Today I'm trying to change the year of a Date object to 2000 in Swift.
今天我试图在 Swift 中将 Date 对象的年份更改为 2000。
let date = Date()
Firstly, I tried with date(bySetting:)
but it does not work with past year. It simply returns nil
首先,我尝试过,date(bySetting:)
但在过去的一年中不起作用。它只是返回 nil
Calendar.current.date(bySetting: .year, value: 2000, of: date)
Secondly, I tried with dateComponents
. The component.year
has changed, but it calendar still returns the original date, very strange !!. No matter what timezone and calendar I use, it still has this problem
其次,我尝试使用dateComponents
. 在component.year
发生了变化,但它仍然日历回到原来的日期,很奇怪!。无论我使用什么时区和日历,它仍然存在这个问题
var component = calendar.dateComponents(in: TimeZone.current, from: base)
component.year = year
Calendar.current.date(from: component)
Finally, I tried to be more explicit, and it works
最后,我尝试更明确,并且有效
var component = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: base)
component.year = year
Calendar.current.date(from: component)
回答by Igor
Or in swift:
或者快速:
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: NSDate.init())
components.day = 17
components.month = 5
components.year = 2013
let date = calendar.dateFromComponents(components)
回答by Pranit
Swift 3.0
Get-Date which having Year, Month & Day -5 from Current Date
Swift 3.0
Get-Date 从当前日期开始具有年、月和日 -5
//CurrentDate
let currentDate = Date()
let gregorianCalendar = Calendar(identifier: .gregorian)
var components = gregorianCalendar.dateComponents([.year, .month, .day], from: currentDate)
// Change int value which you want to minus from current Date.
components.day = components.day!-5
components.month = components.month!-5
components.year = components.year!-5
let date = gregorianCalendar.date(from: components)!
print("Current Date = \(currentDate)")
print("Old Date = \(date)")
Swift 2.0
斯威夫特 2.0
//CurrentDate
let currentDate = NSDate()
let gregorianCalendar = NSCalendar(identifier: .gregorian)
var components = gregorianCalendar.dateComponents([.year, .month, .day], from: currentDate)
// Change int value which you want to minus from current Date.
components.day = components.day!-5
components.month = components.month!-5
components.year = components.year!-5
let date = gregorianCalendar.date(from: components)!
print("Current Date = \(currentDate)")
print("Old Date = \(date)")
回答by Durgaprasad
You need to find numberOfSeconds of today at 0 am and other date numberOfSeconds at 0 am. Find difference between them. Then to numberOfSeconds of 2013-05-17 15:00:12 +0000 add this difference.
您需要在今天上午 0 点找到 numberOfSeconds,在上午 0 点找到其他日期 numberOfSeconds。找出它们之间的区别。然后到 numberOfSeconds of 2013-05-17 15:00:12 +0000 添加此差异。
回答by Saurabh
Why can't you just change the start date with current date and time you desire using the API dateWithString. If not then you can probably look at dateByAddingTimeInterval API of NSDate as well by taking diff of timeinterval between two NSDate
为什么您不能使用 API dateWithString更改具有当前日期和时间的开始日期。如果没有,那么您也可以通过获取两个 NSDate 之间的时间间隔差异来查看 NSDate 的 dateByAddingTimeInterval API
回答by skymook
Swift 5
斯威夫特 5
This first function just lets you get a date from a server string. I only added this just to make it clear what the start date is in a readable format. You don't need this, it is only to help with my answer.
第一个函数只是让您从服务器字符串中获取日期。我添加这个只是为了以可读的格式清楚地说明开始日期是什么。你不需要这个,它只是为了帮助我的回答。
func dateFrom(_ serverDate: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = dateFormatter.date(from: serverDate) {
return date
}
return nil
}
This is the code that gets the time from date
and moves it to today. Something to note: startDate
is set to midnight, so that the time can be added to today.
这是获取时间date
并将其移动到今天的代码。需要注意的是:startDate
设置为午夜,以便可以将时间添加到今天。
let calendar = Calendar.current
if let date = dateFrom("2019-11-17 09:30:00") {
let today = Date()
let startDate = calendar.startOfDay(for: today)
let hours = calendar.component(.hour, from: date)
let mins = calendar.component(.minute, from: date)
if let correctHour = calendar.date(bySetting: .hour, value: hours, of: startDate) {
if let todayWithTime = calendar.date(bySetting: .minute, value: mins, of: correctHour) {
// todayWithTime is today with the correct time
// today at 9:30 am
}
}
}