如何以12小时格式获取当前时间?

时间:2016-11-25 14:22:03

标签: ios swift date

我想以12小时格式获取当前时间。如果时间是18:36我想要格式,那么它应该像下午06:35。为了这个目的,我使用了下面的代码,但它只是没有给我所需的格式。我得到这样的格式。

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date22 = dateFormatter.string(from: date)

3 个答案:

答案 0 :(得分:4)

查看此日期格式guide。 &安培;这site

let dateAsString = "6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.dateFromString(dateAsString)

dateFormatter.dateFormat = "HH:mm"
let date24 = dateFormatter.stringFromDate(date!)

答案 1 :(得分:2)

swift 2:

SET @sk := (SELECT app_users.skeeper_phone as sphone FROM app_users WHERE app_users. app_user_type = 'SKEEPER' LIMIT 1);
SELECT 
acs.id as complainId,
IF(
    (@sk) > 0,
    @sk,
    ''
) as sk_phone,
(
    SELECT 
    IF(
        auu.institute_phone IS NULL,
        auu.department_phone,
        auu.institute_phone
    ) as cphone
    FROM app_users as auu
    WHERE auu.id = acs.app_customer_id
    LIMIT 1
) as cphone,
(
    SELECT auuu.other_user_phone as ephone
    FROM app_users as auuu,app_admin_assign_eng as aase
    WHERE aase.app_complain_service_id = acs.id AND auuu.id = aase.engineer_id
    LIMIT 1
) as ephone,
(
    SELECT auuu.fullname as ename
    FROM app_users as auuu,app_admin_assign_eng as aase
    WHERE aase.app_complain_service_id = acs.id AND auuu.id = aase.engineer_id
    LIMIT 1
) as ename,
(
    SELECT auuu.other_user_phone as ephone
    FROM app_users as auuu,app_admin_assign_eng as aase
    WHERE aase.app_complain_service_id = acs.id AND auuu.id = aase.admin_id
    LIMIT 1
) as aphone
FROM app_complain_services as acs,app_users as au
WHERE 
acs.id = 5
GROUP BY acs.id
快照3:  只需更改一行:

let date = NSDate() // return current time and date let dateFormatter= NSDateFormatter() dateFormatter.dateFormat = "hh:mm a" // for specifying the change to format hour:minute am/pm. let dateInString = dateFormatter.stringFromDate(date) // provide current time in string formatted in 06:35 PM if current time is 18:35 print(dateInString) dateFormatter.dateFormat = "h:mm a"

代码

答案 2 :(得分:1)

我也有同样的问题(从我的后端dateString以24小时格式和UTC格式出现),所以我创建了一个功能完善的功能。看到这个功能: -

func getRequiredFormat(dateStrInTwentyFourHourFomat: String) -> String? {

    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

    if let newDate = dateFormatter.date(from: dateStrInTwentyFourHourFomat) {

        let timeFormat = DateFormatter()
        timeFormat.timeZone = TimeZone.autoupdatingCurrent
        timeFormat.locale = Locale(identifier: "en_US_POSIX")
        timeFormat.dateFormat = "hh:mm a"

        let requiredStr = timeFormat.string(from: newDate)
        return requiredStr
    } else {
        return nil
    }
}