简体   繁体   English

从日期选择器获取不同时区的日期

[英]Getting date from datepicker wrt different timezones

I'm using a standard DatePicker and printing the date on top of it. 我正在使用标准的DatePicker,并在其顶部打印日期。 For some reason my Date Picker has it's timezone set to IST, which maybe because of the locale. 由于某种原因,我的日期选择器将其时区设置为IST,这可能是由于区域设置。

Let's get into an example: 让我们来看一个例子:

DatePicker -> 12:00 PM Date reads -> 06:30:00 +0000 DatePicker-> 12:00 PM日期读取-> 06:30:00 +0000

Which is correct as the date will print UTC time and IST is UTC+5:30 这是正确的,因为日期会显示UTC时间,而ISTUTC + 5:30

Now when I change the timezone of the DatePicker, let's say to London which is GMT+1 , 现在,当我更改DatePicker的时区时,假设伦敦是GMT + 1

DatePicker -> 12:00 PM Date reads -> 06:30:00 +0000 DatePicker-> 12:00 PM日期读取-> 06:30:00 +0000

Where in the date should actually read 11:00:00 日期中实际应读为11:00:00的位置

How I am changing the DatePicker's timezone: 我如何更改DatePicker的时区:

if let tmz = selectTimeZone {

    datePicker.timeZone = tmz
}

i have the same issue sometime before but for the another reason. 我之前有过同样的问题,但出于另一个原因。 Try this hope it will help. 尝试此希望它会有所帮助。

First - 第一-

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" 
var startDate = dateFormatter.string(from: yourdatepicker.date)
startDate = localToUTC(date: startDate)

Second we convert this to local to UTC , here we mention the TimeZone to system time 其次,我们将其转换为本地到UTC,在这里我们将TimeZone转换为系统时间

func localToUTC(date:String) -> String {

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone.system
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dt = dateFormatter.date(from: date)
return dateFormatter.string(from: dt!)
}

Third if you want to conver UTC to your Local time 第三,如果您想将UTC时间转换为您的当地时间

func UTCToLocal(date:String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = NSTimeZone.system
dateFormatter.dateFormat = "hh:mm a"
return dateFormatter.string(from: dt!)
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM