截断 NSDate(时间清零)

发布于 2024-10-02 13:19:24 字数 304 浏览 10 评论 0 原文

我想生成一个新的 NSDate,时间为 0 小时0 分钟0 秒。源日期可以是任何随机的NSDate

有办法实现这一点吗?该文档并没有帮助我解决这个问题。


示例

拥有:2010-10-30 10:14:13 GMT

想要:2010-10-30 00:00:00 GMT

I want to generate a new NSDate with 0 hours, 0 minutes, and 0 seconds for time. The source date can be any random NSDate.

Is there a way to achieve this? The documentation did not help me with this.


Example

Have: 2010-10-30 10:14:13 GMT

Want: 2010-10-30 00:00:00 GMT

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

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

发布评论

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

评论(6

风铃鹿 2024-10-09 13:19:24
unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];

date 是您要删除时间的日期。

这会将日期和时间分开,并使用默认时间 (00:00:00) 创建一个新日期。

编辑

要考虑时区:

NSDate* dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];
unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];

date is the date you want to remove the time from.

This separates the date and time and creates a new date with the default time (00:00:00).

EDIT

To take time zone into account:

NSDate* dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];
浅蓝的眸勾画不出的柔情 2024-10-09 13:19:24

使用 NSCalendar 的 rangeOfUnit:startDate:interval:forDate:。此代码将根据当前时区选择日期边界。如果你想要一个特定的时区,你需要创建一个 NSCalendar 并适当地设置它的时区。

- (NSDate*)boundaryForCalendarUnit:(NSCalendarUnit)calendarUnit
{
    NSDate *boundary;
    [[NSCalendar currentCalendar] rangeOfUnit:calendarUnit startDate:&boundary interval:NULL forDate:self];
    return boundary;
}

- (NSDate*)dayBoundary
{
    return [self boundaryForCalendarUnit:NSDayCalendarUnit];
}

Use NSCalendar's rangeOfUnit:startDate:interval:forDate:. This code will choose the day boundary based on the current time zone. If you want a particular time zone, you need to create an NSCalendar and set its time zone appropriately.

- (NSDate*)boundaryForCalendarUnit:(NSCalendarUnit)calendarUnit
{
    NSDate *boundary;
    [[NSCalendar currentCalendar] rangeOfUnit:calendarUnit startDate:&boundary interval:NULL forDate:self];
    return boundary;
}

- (NSDate*)dayBoundary
{
    return [self boundaryForCalendarUnit:NSDayCalendarUnit];
}
笑看君怀她人 2024-10-09 13:19:24

使用 Swift 3,您可以选择以下四种模式之一来解决您的问题。


#1.使用日历 startOfDay(for:)

startOfDay(for:) 具有以下声明:

func startOfDay(for date: Date) -> Date

返回给定Date的第一个时刻,作为Date

下面的 Playground 代码展示了如何使用此方法:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let newDate = calendar.startOfDay(for: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST

#2。使用日历日期(bySettingHour:分钟:秒:of:matchingPolicy:repeatedTimePolicy:方向:)

date(bySettingHour:min:second:of:matchingPolicy:repeatedTimePolicy:direction:) 具有以下声明:

func date(bySettingHour hour: Int, minute: Int, second: Int, of date: Date, matchingPolicy: Calendar.MatchingPolicy = default, repeatedTimePolicy: Calendar.RepeatedTimePolicy = default, direction: Calendar.SearchDirection = default) -> Date?

返回一个新的Date,表示通过将小时、分钟和秒设置为指定Date上的给定时间计算出的日期。

下面的 Playground 代码展示了如何使用此方法:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let newDate = calendar.date(bySettingHour: 0, minute: 0, second: 0, of: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate!)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST

#3。使用 Calendar dateComponents(_:from:)date(from:) 方法

dateComponents(_:from:) 具有以下声明:

func dateComponents(_ components: Set<Calendar.Component>, from date: Date) -> DateComponents

使用日历时区返回日期的所有日期组成部分。

date(from:) 具有以下内容宣言:

func date(from components: DateComponents) -> Date?

返回从指定组件创建的日期。

下面的 Playground 代码展示了如何使用这些方法:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let components = calendar.dateComponents([.day, .month, .year], from: date)
let newDate = calendar.date(from: components)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate!)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST

#4。使用 NSCalendar range(of:start:interval:for:)

range(of:start:interval:for:) 具有以下声明:

func range(of unit: NSCalendar.Unit, start datep: AutoreleasingUnsafeMutablePointer<NSDate?>?, interval tip: UnsafeMutablePointer<TimeInterval>?, for date: Date) -> Bool

通过引用返回包含给定日期的给定日历单元的开始时间和持续时间。

下面的 Playground 代码展示了如何使用此方法:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current as NSCalendar
var newDate: NSDate?
calendar.range(of: .day, start: &newDate, interval: nil, for: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate as! Date)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST

With Swift 3, you can choose one of the four following patterns in order to solve your problem.


#1. Using Calendar startOfDay(for:)

startOfDay(for:) has the following declaration:

func startOfDay(for date: Date) -> Date

Returns the first moment of a given Date, as a Date.

The Playground code below shows how to use this method:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let newDate = calendar.startOfDay(for: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST

#2. Using Calendar date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)

date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:) has the following declaration:

func date(bySettingHour hour: Int, minute: Int, second: Int, of date: Date, matchingPolicy: Calendar.MatchingPolicy = default, repeatedTimePolicy: Calendar.RepeatedTimePolicy = default, direction: Calendar.SearchDirection = default) -> Date?

Returns a new Date representing the date calculated by setting hour, minute, and second to a given time on a specified Date.

The Playground code below shows how to use this method:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let newDate = calendar.date(bySettingHour: 0, minute: 0, second: 0, of: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate!)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST

#3. Using Calendar dateComponents(_:from:) and date(from:) methods

dateComponents(_:from:) has the following declaration:

func dateComponents(_ components: Set<Calendar.Component>, from date: Date) -> DateComponents

Returns all the date components of a date, using the calendar time zone.

date(from:) has the following declaration:

func date(from components: DateComponents) -> Date?

Returns a date created from the specified components.

The Playground code below shows how to use those methods:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let components = calendar.dateComponents([.day, .month, .year], from: date)
let newDate = calendar.date(from: components)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate!)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST

#4. Using NSCalendar range(of:start:interval:for:)

range(of:start:interval:for:) has the following declaration:

func range(of unit: NSCalendar.Unit, start datep: AutoreleasingUnsafeMutablePointer<NSDate?>?, interval tip: UnsafeMutablePointer<TimeInterval>?, for date: Date) -> Bool

Returns by reference the starting time and duration of a given calendar unit that contains a given date.

The Playground code below shows how to use this method:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current as NSCalendar
var newDate: NSDate?
calendar.range(of: .day, start: &newDate, interval: nil, for: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate as! Date)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST
莫相离 2024-10-09 13:19:24

我知道已经晚了,但现在有更好的方法:
你为什么不直接使用

Swift 2

NSCalendar.currentCalendar().dateBySettingHour(0, minute: 0, second: 0, ofDate: yourDateToZeroOutTime, options: [])

Swift 5

var yourDate = Date() //Or any Date
yourDate  = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: yourDate) ?? yourDate

I know its late, but there are now better methods:
why dont you just use

Swift 2

NSCalendar.currentCalendar().dateBySettingHour(0, minute: 0, second: 0, ofDate: yourDateToZeroOutTime, options: [])

Swift 5

var yourDate = Date() //Or any Date
yourDate  = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: yourDate) ?? yourDate
三五鸿雁 2024-10-09 13:19:24

斯威夫特3

extension Date {
    func trimTime() -> Date {
        var boundary = Date()
        var interval: TimeInterval = 0
        _ = Calendar.current.dateInterval(of: .day, start: &boundary, interval: &interval, for: self)

        return Date(timeInterval: TimeInterval(NSTimeZone.system.secondsFromGMT()), since: boundary)
    }
}

Swift 3

extension Date {
    func trimTime() -> Date {
        var boundary = Date()
        var interval: TimeInterval = 0
        _ = Calendar.current.dateInterval(of: .day, start: &boundary, interval: &interval, for: self)

        return Date(timeInterval: TimeInterval(NSTimeZone.system.secondsFromGMT()), since: boundary)
    }
}
娜些时光,永不杰束 2024-10-09 13:19:24

我将使用描述方法将给定日期作为字符串获取,然后修改该字符串并使用 initWithString 创建新日期。

用字符串初始化:
返回一个 NSDate 对象,该对象使用国际字符串表示格式中给定字符串指定的日期和时间值进行初始化。

  • (id)initWithString:(NSString *)描述
    参数
    描述
    以国际字符串表示格式 YYYY-MM-DD HH:MM:SS ±HHMM 指定日期和时间值的字符串,其中 ±HHMM 是相对于 GMT 的时区偏移量(以小时和分钟为单位)(例如,“2001- 03-24 10:45:32 +0600”)。
    您必须指定格式字符串的所有字段,包括时区偏移量,该偏移量必须具有加号或减号前缀。
    返回值
    使用 aString 指定的日期和时间值初始化的 NSDate 对象。

I would use the description method to get the given date as a string, then modify the string and create your new date with initWithString.

initWithString:
Returns an NSDate object initialized with a date and time value specified by a given string in the international string representation format.

  • (id)initWithString:(NSString *)description
    Parameters
    description
    A string that specifies a date and time value in the international string representation format—YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM is a time zone offset in hours and minutes from GMT (for example, “2001-03-24 10:45:32 +0600”).
    You must specify all fields of the format string, including the time zone offset, which must have a plus or minus sign prefix.
    Return Value
    An NSDate object initialized with a date and time value specified by aString.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文