Correct date time according to device location india or usa

时间:2018-02-15 12:32:08

标签: ios swift nsdateformatter nstimezone

I want to get current time according to my iPhone device I am using code which is giving me yesterday time. My code is

let calendar = Calendar.current
let dateStart = calendar.startOfDay(for: Date())


let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.timeZone = TimeZone.current
let strDate = Date().description(with: Locale.current) //dateFormatter.string(from: dateStart)

print("date Start ***** (dateStart)")

By this I am getting a response :

date Start ***** 2018-02-14 18:30:00 +0000

Can anyone help me how can I get correct time today is 15-02-2018 18:00

Thanks

1 个答案:

答案 0 :(得分:1)

试试这个:

let calendar = Calendar.current
let dateStart = calendar.startOfDay(for: Date()) // Feb 15, 2018 at 12:00 AM"
print(dateStart) // 2018-02-14 18:30:00 +0000

let dateFormatter = DateFormatter()
var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
dateFormatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let newDate = dateFormatter.string(from: dateStart)
print(newDate) //  2018-02-15 00:00

更新:

// Current Time  
dateStart = Date() 
newDate = dateFormatter.string(from: dateStart)
print(newDate) //  2018-02-15 22:30