iOS Swift 将日历组件 int 月转换为中等样式字符串月

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30792264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:22:58  来源:igfitidea点击:

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

iosswiftcalendar

提问by NS1518

I want to display calendar in this format

我想以这种格式显示日历

visible calendar style date

可见日历样式日期

to the user. One option is to use "string range" to get the individual calendar components. The second one is to get it using NSCalendar which to me looks like the better one (is it?). So my code is as below. But there are two problems.

给用户。一种选择是使用“字符串范围”来获取各个日历组件。第二个是使用 NSCalendar 获得它,在我看来它看起来更好(是吗?)。所以我的代码如下。但是有两个问题。

  1. I am not getting the local time form "hour & minute components"
  2. I am getting month in Int. I want it to be in String (month in mediumStyle)
  1. 我没有得到本地时间形式的“小时和分钟组件”
  2. 我在 Int 中获得了一个月。我希望它在字符串中(中型月份)

Anyone know how to get what I need? Image attached is what exactly I want to achieve. There I am using three UILabel one for "date", second for "month, year" and third for "time".

有谁知道如何获得我需要的东西?附上的图片正是我想要实现的。在那里我使用了三个 UILabel,一个用于“日期”,第二个用于“月、年”,第三个用于“时间”。

Any help would be appreciated.

任何帮助,将不胜感激。

var inputDateString = "Jun/12/2015 02:05 Am +05:00"

override func viewDidLoad() {
    super.viewDidLoad()
    let newDate = dateformatterDateString(inputDateString)
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: newDate!)

    let hour = components.hour
    let minutes = components.minute
    let month = components.month
    let year = components.year
    let day = components.day

    println(newDate)
    println(components)
    println(day)     // 12
    println(month)   // 6 -----> Want to have "Jun" here
    println(year)    // 2015
    println(hour)    // 2 ------> Want to have the hour in the inputString i.e. 02
    println(minutes) // 35 ------> Want to have the minute in the inputString i.e.  05
}

func dateformatterDateString(dateString: String) -> NSDate? {
    let dateFormatter: NSDateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MMM/dd/yyyy hh:mm a Z"
    //      dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
    dateFormatter.timeZone = NSTimeZone.localTimeZone()
    return dateFormatter.dateFromString(dateString)
}

回答by Leo Dabus

You can use DateFormatter as follow:

您可以按如下方式使用 DateFormatter:

extension Formatter {
    static let monthMedium: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "LLL"
        return formatter
    }()
    static let hour12: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "h"
        return formatter
    }()
    static let minute0x: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "mm"
        return formatter
    }()
    static let amPM: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "a"
        return formatter
    }()
}
extension Date {
    var monthMedium: String  { return Formatter.monthMedium.string(from: self) }
    var hour12:  String      { return Formatter.hour12.string(from: self) }
    var minute0x: String     { return Formatter.minute0x.string(from: self) }
    var amPM: String         { return Formatter.amPM.string(from: self) }
}


let date = Date()

let dateMonth  = date.monthMedium  // "May"
let dateHour   = date.hour12       // "1"
let dateMinute = date.minute0x     // "18"
let dateAmPm = date.amPM           // "PM"

回答by Fernando Reynoso

NSDateFormatterhas monthSymbols, shortMonthSymbolsand veryShortSymbolsproperties.

NSDateFormattermonthSymbols,shortMonthSymbolsveryShortSymbols属性。

So try this:

所以试试这个:

let dateFormatter: NSDateFormatter = NSDateFormatter()

let months = dateFormatter.shortMonthSymbols
let monthSymbol = months[month-1] as! String // month - from your date components

println(monthSymbol)

回答by A.G

I am adding three types. Have a look.

        //Todays Date
        let todayDate = NSDate()
        let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
        let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: todayDate)
        var (year, month, date) = (components.year, components.month, components.day)
        println("YEAR: \(year)  MONTH: \(month) DATE: \(date)")

        //Making a X mas Yr
        let morningOfChristmasComponents = NSDateComponents()
        morningOfChristmasComponents.year = 2014
        morningOfChristmasComponents.month = 12
        morningOfChristmasComponents.day = 25
        morningOfChristmasComponents.hour = 7
        morningOfChristmasComponents.minute = 0
        morningOfChristmasComponents.second = 0

        let morningOfChristmas = NSCalendar.currentCalendar().dateFromComponents(morningOfChristmasComponents)!
        let formatter = NSDateFormatter()
        formatter.dateStyle = NSDateFormatterStyle.LongStyle
        formatter.timeStyle = .MediumStyle
        let dateString = formatter.stringFromDate(morningOfChristmas)
        print("dateString : \(dateString)")


        //Current month - complete name
        let dateFormatter: NSDateFormatter = NSDateFormatter()
        let months = dateFormatter.monthSymbols
        let monthSymbol = months[month-1] as! String
        println("monthSymbol  : \(monthSymbol)")


Print Results:

YEAR: 2015  MONTH: 10 DATE: 9
dateString : December 25, 2014 at 7:00:00 AM
monthSymbol  : October

回答by cspam

Swift 4.x Solution:

Swift 4.x 解决方案:

//if currentMonth = 1
DateFormatter().monthSymbols[currentMonth - 1]

Answer:

回答:

January

一月

回答by Md. Yamin Mollah

Update Swift 5.x Solution:

更新 Swift 5.x 解决方案:

Today is Monday, 20 April, 2020

今天是 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.

我认为这是最简单和更新的答案。