NSDate set timezone in swift

前端 未结 5 1893
一向
一向 2020-12-10 04:25

how can i return a NSDate in a predefined time zone from a string

let responseString = \"2015-8-17 GMT+05:30\"
var dFormatter = NSDateFormatter()
dFormatter.         


        
5条回答
  •  情歌与酒
    2020-12-10 04:55

    If you always have the same time zone for the input string, you can create two date formatters to output the local time zone (or a specified one):

    let timeFormatterGet = DateFormatter()
    timeFormatterGet.dateFormat = "h:mm a"
    timeFormatterGet.timeZone = TimeZone(abbreviation: "PST")
    
    let timeFormatterPrint = DateFormatter()
    timeFormatterPrint.dateFormat = "h:mm a"
    // timeFormatterPrint.timeZone = TimeZone(abbreviation: "EST") // if you want to specify timezone for output, otherwise leave this line blank and it will default to devices timezone
    
    if let date = timeFormatterGet.date(from: "3:30 PM") {
        print(timeFormatterPrint.string(from: date)). // "6:30 PM" if device in EST
    } else {
       print("There was an error decoding the string")
    }
    

提交回复
热议问题