swift 以字符串形式获取日期和时间

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 以字符串形式获取日期和时间相关的知识,希望对你有一定的参考价值。

//http://www.globalnerdy.com/2016/08/22/how-to-work-with-dates-and-times-in-swift-3-part-2-dateformatter/

static func getDatetimeAsString()->String
{
        let date = Date()
        let calendar = Calendar.current
        let year = calendar.component(.year, from: date)
        let month = calendar.component(.month, from: date)
        let day = calendar.component(.day, from: date)
        let hour = calendar.component(.hour, from: date)
        let minute = calendar.component(.minute, from: date)
        let second = calendar.component(.second, from: date)

        
        return String(day)+"/"+String(month)+"/"+String(year)+" "+String(hour)+":"+String(minute)+String(second)
}

    static func getDateAsString()->String
    {
        let date = Date()
        let calendar = Calendar.current
        let year = calendar.component(.year, from: date)
        let month = calendar.component(.month, from: date)
        let day = calendar.component(.day, from: date)

        return String(day)+"_"+String(month)+"_"+String(year)
    }
    
    
        static private func dateConverter(sdate:String,format:String)->Date
    {
       format=yyyy/MM/dd HH:mm:ss //24h format
      format=yyyy/MM/dd hh:mm:ss //12h format
      sdate = "2015/3/07 19:00:1"

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        print(sdate)
        return dateFormatter.date(from: sdate)!
    }

以上是关于swift 以字符串形式获取日期和时间的主要内容,如果未能解决你的问题,请参考以下文章

Python - 以 YYYY-MM-DD 格式获取昨天的日期作为字符串

Swift 5 中从日期时间字符串到当前时间的天数时差

Swift Core Data Fetch 按日期和时间存储为字符串并排序

swift Date

如何在 swift 中从两天中获取日期名称

C语言如何返回格式化日期时间?(将日期和时间以字符串格式输出)ctime()asctime()localtime()