我将日期和时间分成不同的字符串,并使用日期格式器将它们以日期格式组合在一起。在此之后,我要向结果日期添加30天。现在,我尝试再次使用dateFormatter,但是无论如何,它都会导致nil(即使不是nil)。我究竟做错了什么?
//GET TIME AND DATE FROM TWO STRINGS
var timeStarting = "10:50"
var dateStarting = "03/10/2016"
let date = Date()
let timeStamp = NSDate().timeIntervalSince1970
let dateFormater = DateFormatter()
dateFormater.dateStyle = .short
dateFormater.timeStyle = .none
dateFormater.dateFormat = "dd/MM/yyyy HH:mm"
var timeAndDate = "\(dateStarting) \(timeStarting)"
let endingDate : Date = dateFormater.date(from: "\(timeAndDate)")!
//ADD 30 DAYS TO ENDING DATE
var numberOfDays = "30"
let thirtyDaysBeforeToday = Calendar.current.date(byAdding: .day, value: Int(numberOfDays)!, to: endingDate)
var stringFromThityDaysBefore : String = "\(thirtyDaysBeforeToday!)"
//FORMAT AGAIN TO SHOW THE DATE IN AS (EX.: 13.10.2016)
let dateFormater2 = DateFormatter()
dateFormater2.isLenient = true
dateFormater2.dateStyle = .short
dateFormater2.timeStyle = .none
dateFormater2.dateFormat = "dd.MM.yy"
var newDates : Date = dateFormater2.date(from: "\(stringFromThityDaysBefore)")!
(结果示例:2016年10月13日)-结束日期后30天
答案 0 :(得分:1)
这里有很多问题,并且有很多不必要的代码。
stringFromThityDaysBefore
。 thirtyDaysBeforeToday
后30天Date
已经endingDate
。dateFormat
和date/timeStyle
。只能设置一个。Date
转换为String
,然后尝试使用第二个日期格式化程序解析该字符串。这是固定代码:
let timeStarting = "10:50"
let dateStarting = "03/10/2016"
let dateFormater = DateFormatter()
dateFormater.dateFormat = "dd/MM/yyyy HH:mm"
dateFormater.locale = Locale(identifier: "en_US_POSIX")
let timeAndDate = "\(dateStarting) \(timeStarting)"
let endingDate = dateFormater.date(from: timeAndDate)!
//ADD 30 DAYS TO ENDING DATE
let numberOfDays = 30
let thirtyDaysAfter = Calendar.current.date(byAdding: .day, value: numberOfDays, to: endingDate)!
//FORMAT AGAIN TO SHOW THE DATE IN AS (EX.: 13.10.2016)
let dateFormater2 = DateFormatter()
dateFormater2.dateFormat = "dd.MM.yy"
let newDateString = dateFormater2.string(from: thirtyDaysAfter)
给出02.11.16
对newDateString
的结果。
最后要考虑的一件事-不要在第二个日期格式化程序上使用dateFormat
。使用date/timeStyle
。最好在希望显示给用户的任何日期使用一种样式。这样可以确保其格式最适合用户的语言环境。