Last active
December 16, 2015 02:47
-
-
Save negibouze/aa28c87c0271c2b8f9df to your computer and use it in GitHub Desktop.
NSDateFormatter extension
This file contains hidden or 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
extension NSDateFormatter { | |
/** | |
カレンダー, ロケール, タイムゾーンを指定して初期化 | |
@param calendarIdentifier カレンダーの識別子 (NSCalendarIdentifierGregorian...) | |
@param localeIdentifier ロケールの識別子 (ja_JP, en_US_POSIX...) | |
@param abbreviation タイムゾーンの略称 (GMT, JST...) | |
*/ | |
convenience init(calendarIdentifier: String, localeIdentifier: String = "ja_JP", abbreviation: String = "GMT") { | |
self.init() | |
if let cal = NSCalendar(calendarIdentifier: calendarIdentifier) { | |
self.calendar = cal | |
} | |
self.locale = NSLocale(localeIdentifier: localeIdentifier) | |
if let tz: NSTimeZone? = NSTimeZone(abbreviation: abbreviation) { | |
self.timeZone = tz | |
} | |
} | |
/** | |
日付文字列を指定フォーマットの日付文字列に変換する | |
@param dateStr 変換元の日付文字列(yyyy-MM-dd HH:mm:ss.SSS'+09') | |
@param format 変換後の形式 | |
@param returnOfFailure 失敗時に返す値 (未設定時はdateStr) | |
*/ | |
func stringFromString(dateStr: String, format: String = "yyyy年MM月", returnOfFailure: String? = nil) -> String { | |
self.dateFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss'.'SSS'+09'" | |
guard let date = self.dateFromString(dateStr) else { | |
return returnOfFailure ?? dateStr | |
} | |
self.dateFormat = format | |
return self.stringFromDate(date) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment