How do I get the current Date in short format in Swift

前端 未结 7 784
北荒
北荒 2020-11-22 15:10

In the images below you can see the code I wrote and the values of all the variables:

class fun getCurrentShortDate() -> String {
    var todaysDate = NSD         


        
7条回答
  •  有刺的猬
    2020-11-22 15:50

    Here's the way Apple suggests

        let formatter = DateFormatter()
        formatter.locale = Locale.current
        formatter.dateStyle = .short
        let dateString = formatter.string(from: date)
    

    or if the pre-defined format of .short, .medium, .long and .full are quite right create the template in a locale

        let formatter = DateFormatter()
        formatter.locale = Locale.current
        formatter.setLocalizedDateFormatFromTemplate("MM/dd/yyyy")
        let dateString = formatter.string(from: date)
    

    Here's the link

提交回复
热议问题