[英]How to get local time zone date in swift 3
I am getting year,month and day from a given date in this way.我以这种方式从给定日期获取年、月和日。
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day=components.day
But I'm getting one day ahead from my current day.但我比今天提前了一天。 How can I solve this?
我该如何解决这个问题?
let date = Date().description(with: Locale.current)
print("date ---> \(date)")
Result: date ---> Tuesday, June 20, 2017 at 4:35:15 PM India Standard Time
结果:日期---> 2017年6月20日星期二下午4:35:15印度标准时间
I'm getting perfect system/local time. 我正在获得完美的系统/当地时间。
You code is working, 你的代码工作正常,
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: today)
let day = components.day
let hour = components.hour
let minute = components.minute
print("day = \(day)\nhour = \(hour)\nminute = \(minute)")
Result:
结果:
day = Optional(20)day =可选(20)
hour = Optional(16)小时=可选(16)
minute = Optional(35)分钟=可选(35)
As per the documentation : 根据文件 :
If you want “date information in a given time zone” in order to display it, you should use DateFormatter to format the date.
如果要显示“给定时区中的日期信息”以显示它,则应使用DateFormatter格式化日期。
eg: 例如:
// If date is "Dec 7, 2018 at 6:34 AM" UTC
let today=Date() // is always UTC
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day = components.day // Is 7
// To print with local version
let myFormatter = DateFormatter()
myFormatter.timeZone = TimeZone(secondsFromGMT: 3600*10)
myFormatter.dateFormat = "dd"
print(myFormatter.string(from: today)) // prints "07\n"
myFormatter.timeZone = TimeZone(secondsFromGMT: -3600*11)
print(myFormatter.string(from: today)) // prints "06\n"
Get Local Date and Time获取本地日期和时间
Swift 5:斯威夫特 5:
let today = Date()
let timeZone = Double(TimeZone.current.secondsFromGMT(for: today))
let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZone), to: today) ?? Date()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.