Sample code to get the current date, day of the week, and current time in Swift4.1.
You can get it as a string of the following format.
Thu, Apr 03, 2018
19:03:34
Here is the sample code to get it in the form shown above.
If you use Calendar.current, there is a possibility that you will get it in Japanese calendar (Heisei 00 year) depending on the setting (you want 2018/04/03, but 30/04/03 comes back), so it is better to get it in Gregorian calendar.
On the other hand, if you want a Japanese calendar, there is a way to get a Japanese calendar.
This site is detailed.
Swift 3 の日時操作チートシート
Other sites that I found helpful
Swift3での日時に関する処理
【Swift3】現在時刻の取得とDataFormatterでの文字列化
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 UIKit | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
self.view.backgroundColor = .white | |
print(getDateString()) //2018/05/10 (木) | |
print(getDateString2()) //2018年5月10日 | |
print(getTimeString()) //09:27:08 | |
} | |
func getDateString() -> String { | |
let date = NSDate() | |
let formatter = DateFormatter() | |
formatter.dateFormat = "yyyy/MM/dd" | |
let dateStr = formatter.string(from: date as Date) | |
//あまり良く無い例 | |
/* | |
let cal = NSCalendar(calendarIdentifier: .gregorian) | |
let weeks = ["日","月","火","水","木","金","土"] | |
let comp = cal?.components(NSCalendar.Unit.weekday, from: date as Date) | |
let weekIdx = comp?.weekday | |
var weekStr = weeks[weekIdx! - 1] | |
*/ | |
//ローカライズなどを考えてこっちを使おう! | |
formatter.locale = NSLocale(localeIdentifier: "ja_JP") as Locale? | |
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "EEEEE", options: 0, locale: Locale.current) | |
let weekStr = formatter.string(from: date as Date) | |
return dateStr + " (" + weekStr + ")" | |
} | |
func getDateString2() -> String { | |
let date = NSDate() | |
let formatter = DateFormatter() | |
//あまり良く無い例 | |
//formatter.dateFormat = "yyyy年MM月dd日" | |
//ローカライズなどを考えてこっちを使おう! | |
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "ydMMM", options: 0, locale: Locale(identifier: "ja_JP")) | |
return formatter.string(from: date as Date) | |
} | |
func getTimeString() -> String { | |
let date = NSDate() | |
let formatter = DateFormatter() | |
formatter.dateFormat = "HH:mm:ss" | |
return formatter.string(from: date as Date) | |
} | |
} |