I came across an issue when I was doing an online exercise for Swfit on Exercism. However, the code I wrote haven't been able to pass the test suite provided by the website. The problem seems to lie with the date format of the resulting date object wrapped in an optional.
I was able to get the formate of incoming dateString
to conform to the test suite date format. However, I was unable to make the destinationDate
also conform to the test suite date format.
I tried to use the ISO8601DateFormatter
, but the compiler on my old Mac doesn't suport this class. I tried my code on online Swift compilers, but the results haven't been satisfying so far, either.
The exercise is described as follows:
Calculate the moment when someone has lived for 10^9 seconds.
A gigasecond is 10^9 (1,000,000,000) seconds.
I wrote the following code:
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
}
The test suite for this exercise provided by the website is as follows:
//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),
])
Please help see what problem there is with my code. Thank you very much!