Created
January 4, 2019 11:03
-
-
Save d-date/1767419a2a278a862f463e70379fbbfe to your computer and use it in GitHub Desktop.
DateIntervalで遊んだ(友達待ってる間の暇つぶし) #CodePiece
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Date { | |
var elasticDateFormat: String { | |
let calendar = Calendar.current | |
let date = Date() | |
let dateInterval = calendar.dateInterval(of: .month, for: self) | |
if calendar.dateInterval(of: .day, for: self)!.contains(date) { | |
return "HH:mm" | |
} else if calendar.dateInterval(of: .month, for: self)!.contains(date) { | |
return "M/d" | |
} else { | |
return "yyyy/MM/dd" | |
} | |
} | |
func toString(format: String) -> String { | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = format | |
return dateFormatter.string(from: self) | |
} | |
} | |
let date = Date().addingTimeInterval(-86401) | |
let format = date.elasticDateFormat | |
let string = date.toString(format: format) | |
print(string) // 1/3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment