UTC日期到当前TimeZone字符串和结果StringDate到当前TimeZone日期

时间:2017-03-08 11:31:07

标签: ios iphone date swift3 nsdateformatter

我以UTC格式获取当前日期,然后将其转换为Local TimeZone,结果以字符串形式显示。

现在,我将结果字符串日期转换为具有相同本地时区的日期,但它以UTC格式提供日期。

以下是我正在使用的代码:

    print("current date :\( Date())") //current date : 2017-03-08 11:11:12 +0000

    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss Z"
    let localDate : String = dateFormatter.string(from: Date())

    print("localDate date :\(localDate)") // localDate date: 08-03-2017 16:41:12 +0530

    let dateFormatter1 = DateFormatter()
    dateFormatter1.timeZone = TimeZone.current
    dateFormatter1.dateFormat = "dd-MM-yyyy HH:mm:ss Z"
    let dateCurrent = dateFormatter1.date(from: localDate)!

    print("dateCurrent date :\(dateCurrent)") // dateCurrent date: 2017-03-08 11:11:12 +0000

dateCurrent

我想要

08-03-2017 16:41:12 +0530

仅类型为Date而非String类型。

我哪里出错?

4 个答案:

答案 0 :(得分:1)

感谢大家的回答,

我挖出来找到了解决办法。我在这里分享代码。

<form method="post" action="" class="form-horizontal">
    {% csrf_token %}
    {% bootstrap_form form_extended layout='horizontal'%}
    {% bootstrap_button "Zatwierdź" size='large' button_type="submit" button_class="btn-primary" %}
</form>

答案 1 :(得分:0)

这是Date个对象的工作方式。您只需保留日期对象,直到需要将其输出到用户或API,此时您可以将其转换为适当时区的字符串。

Date对象基本上只是用一些辅助方法包装一个unix时间戳来处理它。

答案 2 :(得分:0)

试试这个,希望有所帮助

let date: String =  "dd-MM-yyyy HH:mm:ss Z"
    var dateArr = date.components(separatedBy: " ")
    let dateCurrent  = (dateArr [0] )
    print(dateCurrent)

答案 3 :(得分:0)

dateFormatter 问题。这是我将UTC转换为本地和本地UTC的代码:

    convertUTCtoLocal(strUTCDate: "09-03-2017 03:54:00")
    convertLocalToUTC(strUTCDate: "09-03-2017 09:24:00")

将UTC转换为本地

    func  convertUTCtoLocal(strUTCDate: String){
    let dateFormater : DateFormatter = DateFormatter();
    dateFormater.timeZone = TimeZone(abbreviation: "UTC")
    dateFormater.dateFormat = "dd-MM-yyyy HH:mm:ss"

    let dateFromString = dateFormater.date(from: strUTCDate)

    dateFormater.timeZone = NSTimeZone.local as TimeZone!
    dateFormater.dateFormat = "dd-MM-yyyy HH:mm:ss"

    let localData = dateFormater.string(from: dateFromString!)
    print("Your local date is \(localData)")        
}

将本地转换为UTC

   func  convertLocalToUTC(strUTCDate: String){
    let dateFormater : DateFormatter = DateFormatter();
    dateFormater.dateFormat = "dd-MM-yyyy HH:mm:ss"
    dateFormater.timeZone = NSTimeZone.local as TimeZone!

    let dateFromString = dateFormater.date(from: strUTCDate)

    dateFormater.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!;
    dateFormater.dateFormat = "dd-MM-yyyy HH:mm:ss"

    let localData = dateFormater.string(from: dateFromString!)
    print("Your UTC date is \(localData)")        
}