【发布时间】:2020-07-14 04:40:11
【问题描述】:
我在Exercism 上为 Swfit 进行在线练习时遇到了一个问题。但是,我写的代码一直无法通过网站提供的测试套件。问题似乎在于包含在可选中的结果日期对象的日期格式。
我能够获得传入dateString 的格式以符合测试套件日期格式。但是,我无法使 destinationDate 也符合测试套件日期格式。
我尝试使用ISO8601DateFormatter,但我的旧 Mac 上的编译器不支持此类。我在在线 Swift 编译器上尝试了我的代码,但到目前为止结果也不令人满意。
练习描述如下:
计算某人活了 10^9 秒的时刻。
千兆秒是 10^9 (1,000,000,000) 秒。
我写了以下代码:
import Foundation
func Gigasecond(from dateString: String) -> Date? {
let GIGASECOND: Double = 1_000_000_000
let RFC3339DateFormatter = DateFormatter()
RFC3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss"
let sourceDate = RFC3339DateFormatter.date(from: dateString)
var destinationDate: Date? = Date(timeInterval: GIGASECOND, since: sourceDate ?? Date())
let destDateString = RFC3339DateFormatter.string(from: destinationDate ?? Date())
destinationDate = RFC3339DateFormatter.date(from: destDateString)
return destinationDate
}
网站提供的本次练习的测试套件如下:
//GigasecondTests.swift
import XCTest
@testable import Gigasecond
class GigasecondTests: XCTestCase {
func test1 () {
let gs = Gigasecond(from: "2011-04-25T00:00:00")?.description
XCTAssertEqual("2043-01-01T01:46:40", gs)
}
func test2 () {
let gs = Gigasecond(from: "1977-06-13T00:00:00")?.description
XCTAssertEqual("2009-02-19T01:46:40", gs)
}
func test3 () {
let gs = Gigasecond(from: "1959-07-19T00:00:00")?.description
XCTAssertEqual("1991-03-27T01:46:40", gs)
}
func testTimeWithSeconds () {
let gs = Gigasecond(from: "1959-07-19T23:59:59")?.description
XCTAssertEqual("1991-03-28T01:46:39", gs)
}
func testFullTimeSpecified () {
let gs = Gigasecond(from: "2015-01-24T22:00:00")?.description
XCTAssertEqual("2046-10-02T23:46:40", gs)
}
func testFullTimeWithDayRollOver () {
let gs = Gigasecond(from: "2015-01-24T23:59:59")?.description
XCTAssertEqual("2046-10-03T01:46:39", gs)
}
static var allTests: [(String, (GigasecondTests) -> () throws -> Void)] {
return [
("test1 ", test1 ),
("test2 ", test2 ),
("test3 ", test3 ),
("testTimeWithSeconds ", testTimeWithSeconds ),
("testFullTimeSpecified ", testFullTimeSpecified ),
("testFullTimeWithDayRollOver ", testFullTimeWithDayRollOver ),
]
}
}
// LinuxMain.swift
import XCTest
@testable import GigasecondTests
XCTMain([
testCase(GigasecondTests.allTests),
])
请帮忙看看我的代码有什么问题。非常感谢!
【问题讨论】:
-
您使用了错误的 dateFormat
hh是 01-12 您需要的是HH00-23。dateFormat = "yyyy-MM-dd'T'HH:mm:ss"。请注意,描述将导致 UTC 日期描述(不是当前时区) -
您的方法必须返回
Date吗?从测试用例来看,它应该返回一个String... -
@Sweeper 如果 OP 使用日期,则测试用例将永远不值得推力。它总是会失去精度。他需要使用日期格式化程序从解析的日期生成字符串以测试是否相等
-
@LeoDabus 是的,这就是我的意思......
标签: swift dateformatter