iOS Swift converting calendar component int month to medium style string month

后端 未结 5 2102
后悔当初
后悔当初 2020-12-09 16:25

I want to display calendar in this format

\"visible

to the user. One option is to

5条回答
  •  盖世英雄少女心
    2020-12-09 17:11

    Update Swift 5.x Solution:

    Today is Monday, 20 April, 2020

        let date = Date() // get a current date instance
        let dateFormatter = DateFormatter() // get a date formatter instance
        let calendar = dateFormatter.calendar // get a calendar instance
    

    Now you can get every index value of year, month, week, day everything what you want as follows:

        let year = calendar?.component(.year, from: date) // Result: 2020
        let month = calendar?.component(.month, from: date) // Result: 4
        let week = calendar?.component(.weekOfMonth, from: date) // Result: 4
        let day = calendar?.component(.day, from: date) // Result: 20
        let weekday = calendar?.component(.weekday, from: date) // Result: 2
        let weekdayOrdinal = calendar?.component(.weekdayOrdinal, from: date) // Result: 3
        let weekOfYear = calendar?.component(.weekOfYear, from: date) // Result: 17
    

    You can get an array of all month names like:

        let monthsWithFullName = dateFormatter.monthSymbols // Result: ["January”, "February”, "March”, "April”, "May”, "June”, "July”, "August”, "September”, "October”, "November”, "December”]
        let monthsWithShortName = dateFormatter.shortMonthSymbols // Result: ["Jan”, "Feb”, "Mar”, "Apr”, "May”, "Jun”, "Jul”, "Aug”, "Sep”, "Oct”, "Nov”, "Dec”]
    

    You can format current date as you wish like:

        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let todayWithTime = dateFormatter.string(from: date) // Result: "2020-04-20 06:17:29"
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let onlyTodayDate = dateFormatter.string(from: date) // Result: "2020-04-20"
    

    I think this is the most simpler and updated answer.

提交回复
热议问题