Swift中是否有只限日期(无时间)的课程?

ttisahbt  于 2022-12-26  发布在  Swift
关注(0)|答案(9)|浏览(108)

Swift中是否有一个只有日期(没有时间)的类?(或Foundation类)
(as题外话,如果没有,但有一个众所周知的/流行的开源库,实现了这一点,如果你可以提到这一点)

hiz5n14c

hiz5n14c1#

Foundation中没有只包含日期的类,但是你可以使用Calendar从Date对象中剥离时间。在Swift 4中:

func stripTime(from originalDate: Date) -> Date {
    let components = Calendar.current.dateComponents([.year, .month, .day], from: originalDate)
    let date = Calendar.current.date(from: components)
    return date!
}

或作为扩展名:

extension Date {

    func stripTime() -> Date {
        let components = Calendar.current.dateComponents([.year, .month, .day], from: self)
        let date = Calendar.current.date(from: components)
        return date!
    }

}
v09wglhw

v09wglhw2#

Foundation框架中没有只包含日期的类。
这是获取NSDate对象的仅日期表示形式的快速方法:

let now = NSDate()

let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle

print(dateFormatter.stringFromDate(now)) // Mar 3, 2016

NSDate总是有时间的,因为日期是一个单一的时间点。如果你愿意,你可以创建一个没有时间组件的日期,但它通常默认为12AM:

let dateString = "2016-03-03"
let dateFromStringFormatter = NSDateFormatter()
dateFromStringFormatter.dateFormat = "yyyy-MM-dd"

let dateFromString = dateFromStringFormatter.dateFromString(dateString)
// dateFromString shows "Mar 3, 2016, 12:00 AM"

适用于Swift 3.0+

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

// optional
let date = dateFormatter.date(from: "2016-03-03") // Mar 3, 2015 at 12:00 AM
yzuktlbb

yzuktlbb3#

雨燕3.0

let date = Date()

let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none
dateFormatter.dateStyle = DateFormatter.Style.short

dateFormatter.string(from: date) // 12/15/16
camsedfj

camsedfj4#

如果您想在Swift 4中获取一个Date对象,比如当您试图在核心数据中存储一个Date对象时,您可以使用这个方法。

private func getDate() -> Date {
let today = Date()

let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none
dateFormatter .dateStyle = DateFormatter.Style.short

let dateAsString = dateFormatter.string(from: today)

return dateFormatter.date(from: dateAsString)!
}

基于“约翰·R·佩里”的回答。

k97glaaz

k97glaaz5#

我使用了这个线程中的一个解决方案(运行良好),后来发现swift提供了以下功能:

Locale.current.calendar.startOfDay(for: Date()) // "Sep 10, 2022 at 12:00 AM"

它的作用似乎与Date扩展相同:

Date().stripTime() // "Sep 10, 2022 at 12:00 AM"
yqyhoc1h

yqyhoc1h6#

我会说日期值的字符串指定为“YYYY-MM-DD”+ NSCalendar。标识符可以表示一个日期。
有了这个,你就可以将这个日期转换成任何其他日历。

wyyhbhjk

wyyhbhjk7#

我知道已经有一些很好的答案了。。只是想把这个传进来,它打印“真”,所以如果你使用组件或者只是把时间设置为00:00:00基本上是一样的...

let startComp = Calendar.current.dateComponents([.year, .month, .day], from: Date())
let first = Calendar.current.date(from: startComp)!

print(first == Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date()))

希望这对某人有帮助:)

nfeuvbwi

nfeuvbwi8#

Swift Standard库或Foundation中没有仅日期(无时间)类型(自iOS 13起)。
下面是一个类型CalendarDate,您可以使用它在Swift中将日期表示为年、月、日:
也可通过Swift Package Manager访问以下网址:CalendarDate

import Foundation

/**
 CalendarDate is a Swift type that represents a Date as year, month and day value.
 Includes support for formatting as a ISO 8601 string ('yyyy-mm-dd') and JSON coding.
 */
public struct CalendarDate: Equatable, Hashable {

    public let year, month, day: Int

    public static var today: CalendarDate {
        CalendarDate(date: Date())
    }

    public init(year: Int, month: Int, day: Int) {
        self.year = year
        self.month = month
        self.day = day
    }

    public init(date: Date) {
        let calendar = Calendar.current
        self.year = calendar.component(.year, from: date)
        self.month = calendar.component(.month, from: date)
        self.day = calendar.component(.day, from: date)
    }

    public var date: Date {
        DateComponents(calendar: Calendar.current, year: self.year, month: self.month, day: self.day).date!
    }

}

extension CalendarDate: LosslessStringConvertible {

    public init?(_ description: String) {
        if let date = Self.formatter.date(from: description) {
            self.init(date: date)
        } else {
            return nil
        }
    }

    public var description: String {
        Self.formatter.string(from: self.date)
    }

    private static let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }()
}

extension CalendarDate: Codable {

    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let string = try container.decode(String.self)

        guard let value = CalendarDate(string) else {
            throw DecodingError.dataCorruptedError(
                in: container,
                debugDescription: "Not a valid calendar date: \"\(string)\""
            )
        }

        self = value
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(self.description)
    }

}
z9ju0rcb

z9ju0rcb9#

正如在其他回答中提到的,没有“仅日期”类型。如果您的目标是显示与用户的区域设置相关的当前日期,则应采用以下方法:

//Returns 12/23/2022
DateFormatter.localizedString(from: Date.now, dateStyle: .short, timeStyle: .none)

 //Returns 23 Dec 2022
DateFormatter.localizedString(from: Date.now, dateStyle: .medium, timeStyle: .none)

相关问题