如何在swift 3

时间:2017-06-20 10:49:16

标签: ios date swift3

我以这种方式从特定日期开始年,月,日。

let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)    

let day=components.day

但是从现在开始,我提前一天。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

let date = Date().description(with: Locale.current)
print("date ---> \(date)")
  

结果:日期---> 2017年6月20日星期二下午4:35:15印度标准时间

我正在获得完美的系统/当地时间。

你的代码正常,

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)")
  

结果:
day =可选(20)
小时=可选(16)
分钟=可选(35)

答案 1 :(得分:0)

按照documentation

  

如果要“给定时区中的日期信息”以便   显示它,您应该使用DateFormatter格式化日期。

例如:

// 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"