从字符串转换为日期,从日期转换为字符串时间格式将更改原始数据。
还通过给出小时和分钟来尝试dateComponents
var calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: calFrom)
calendar.timeZone = .current
// Specify date components
var dateComponents:DateComponents = calendar.dateComponents([.year, .month, .day, .hour], from: Date())
dateComponents.year = components.year
dateComponents.month = components.month
dateComponents.day = components.day
dateComponents.hour = 08//Cutomised hour
dateComponents.minute = 34//Cutomised Minutes
// Create date from components
let someDateTime = calendar.date(from: dateComponents)
print(someDateTime!)
实际输出:
2019-04-02 03:04:00 +0000
预期输出:
2019-04-02 08:34:00 +0000
我也尝试了以下代码。将日期转换为字符串,然后将小时和分钟手动添加到字符串,然后转换回日期。
let calFrom = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
var calFromDate = formatter.string(from: calFrom)
calFromDate = calFromDate + " 09" + ":30"
print(calFromDate)
//Output 02/04/2019 09:30
formatter.dateFormat = "dd/MM/yyyy hh:mm"
formatter.locale = Locale.current// set locale to reliable US_POSIX
let date1 = formatter.date(from: calFromDate)
print(date1!)
实际输出:
2019-04-02 04:00:00 +0000
预期输出:
02/04/2019 09:30
如何获取输出中给出的确切时间?
答案 0 :(得分:0)
Date
用于更新hour
和minute
组件具有UTC
时区,因此calendar
也应具有与下面相同的timeZone
,
calendar.timeZone = TimeZone(abbreviation: "UTC")!