我有一个应用程序,可以计算两个日期之间的差异。如果用户输入的开始日期晚于结束日期,则结果为否定。这可以。但是,我的应用程序生成的字符串包含两个减号。我想消除第二个减号,这样就不用说" -17周+ - 4天"它说" -17周+4天"。
我需要从结果中删除第二个减号。我知道这是通过字符串操作实现的,但我不知道如何做到这一点。在实现字符串操作之前,我需要首先检查输出的字符串是否为负值。如果有人能指出我正确的方向,我将非常感激。
我需要实现此字符串操作以删除第二个减号的方法如下:
@IBAction func calculateWeeksAndDays(sender: UIButton) {
if startDateTextField.text == "" || endDateTextField == "" {
let alert2 = UIAlertController(title: "Oops!", message: "Please Select an End Date!", preferredStyle: UIAlertControllerStyle.Alert)
alert2.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert2, animated: true, completion: nil)
}
else {
let start = String(startDateTextField.text!)
let end = String(endDateTextField.text!)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
guard let startDate = dateFormatter.dateFromString(start), endDate = dateFormatter.dateFromString(end) else {
return
}
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
let days = components.day
let weeks = components.day / 7
let weeksanddays = days % 7
let newString = "\(weeks) weeks + \(weeksanddays) days"
resultWeeksAndDays.text = newString
}
}
答案 0 :(得分:3)
您可以使用abs()
,它会返回绝对值,这对string
很有用。
let newString = "\(weeks) weeks + \(abs(weeksanddays)) days"
检查某些内容是否为负面:
if weeks < 0 {
// do stuffs
}
答案 1 :(得分:1)
如果您可以在输出字符串中使用and
而不是+
,则可以使用NSDateComponentsFormatter
。它会自动处理签名问题。
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Full
formatter.allowedUnits = [.Day]
let onlyDaysString = formatter.stringFromDateComponents(components)
formatter.allowedUnits = [.Day, .WeekOfMonth]
let daysAndWeeksString = formatter.stringFromDateComponents(components)