Skip to content

Instantly share code, notes, and snippets.

@lutluthfi
Last active September 12, 2020 07:24
Show Gist options
  • Save lutluthfi/cb4402d7048017b486ad677ee2f73d83 to your computer and use it in GitHub Desktop.
Save lutluthfi/cb4402d7048017b486ad677ee2f73d83 to your computer and use it in GitHub Desktop.
Swift Date Extension
import Foundation
extension Date {
func formatted(
components: [FormatterComponent]
) -> String {
let dateFormatter = DateFormatter()
var dateFormat: String = ""
for (index, component) in components.enumerated() {
dateFormat = index == .zero ?
component.rawValue :
dateFormat + component.rawValue
}
dateFormatter.dateFormat = dateFormat
return dateFormatter.string(from: self)
}
enum FormatterComponent: String, CaseIterable {
case dayOfMonth = "d"
case dayOfMonthPadding = "dd"
case dayOfWeekInMonth = "F"
case dayOfWeekAbbreviationName = "E"
case dayOfWeekWideName = "EEEE"
case dayOfWeekNarrowName = "EEEEE"
case dayOfWeekShortName = "EEEEEE"
case monthOfYearSingle = "M"
case monthOfYearDouble = "MM"
case monthOfYearShorthandName = "MMM"
case monthOfYearFullName = "MMMM"
case monthOfYearNarrowName = "MMMMM"
case yearFullDigits = "yyyy"
case yearTwoDigits = "yy"
case hour12 = "h"
case hour12Padding = "hh"
case hour24 = "H"
case hour24Padding = "HH"
case meridiem = "a"
case minute = "m"
case minutePadding = "mm"
case second = "s"
case secondPadding = "ss"
case millisecond = "SSS"
case dash = "-"
case dot = "."
case colon = ":"
case comma = ","
case underscore = "_"
case whitespace = " "
}
}
import XCTest
@testable import {your_project_name}
final class DateTests: XCTestCase {
func testFormattedDate_whenFormatterComponentFilled_thenResultIsCorrect() {
// Given
// Timestamp is Saturday, September 12, 2020 2:21:24 PM GMT+07:00
let now = Date(timeIntervalSince1970: 1599895284)
// When
let formatted = now.formatted(
components: [
.dayOfWeekAbbreviationName,
.whitespace,
.dayOfMonth,
.comma,
.whitespace,
.monthOfYearFullName,
.whitespace,
.yearFullDigits,
.whitespace,
.hour12Padding,
.colon,
.minutePadding,
.whitespace,
.meridiem
]
)
// Then
let expressionResult = formatted
let expectedExpressionResult = "Sat 12, September 2020 02:21 PM"
XCTAssertEqual(expressionResult, expectedExpressionResult)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment