NSDateFormatter无法正确格式化日期和时间

时间:2015-04-13 08:23:52

标签: swift nsdateformatter uilocalnotification ios8.2 xcode6.3

在我的应用中,我为某些活动设置了本地通知。但是,NSDateFormatter未正确格式化日期和时间。当我格式化日期时,它提前3小时。同样,当我使用NSDate()获取当前时间时,它比UTC提前3小时。我的应用程序中的另一个事件遇到了同样的问题,但我可以通过添加dateFormatter.timeZone = NSTimeZone(name: "GMT")来解决它。当前问题与以下代码有关:

var dateFormatter1 = NSDateFormatter()
var dateFormatter2 = NSDateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd"
dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm"

let mainItemList: Array<BagItem> = self.GetMainItemsInfoInBag()
for(item) in mainItemList
{
    let dateString = dateFormatter1.stringFromDate(item.date) + " " + item.time
    // Send servey notification 
    let serveyNotificationTime = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitHour, value: Int((120 + item.itemService.duration) / 60), toDate: dateFormatter2.dateFromString(dateString)!, options: NSCalendarOptions.WrapComponents)

    self.SetUpLocalNotification(serveyNotificationTime, message: "Do you want to join to the servey?": true)

    // if time for now is earlier than reservation time - 1 based on hour, set reminder notification.
    if(NSDate().dateByAddingTimeInterval(3*60*60).compare(NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitHour, value: -1, toDate: dateFormatter2.dateFromString(dateString)!, options: NSCalendarOptions.WrapComponents)!) == NSComparisonResult.OrderedAscending)
    {
         let reminderNotificationTime = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitHour, value: -1, toDate: dateFormatter2.dateFromString(dateString)!, options: NSCalendarOptions.WrapComponents)
         self.SetUpLocalNotification(reminderNotificationTime, message: message, withCategory: false)
    }
}

// Set Up Local Notifications
private func SetUpLocalNotification(notificationTime: NSDate!, message: String!, withCategory: Bool!)
{
    var app: UIApplication = UIApplication.sharedApplication()
    var notifyAlarm: UILocalNotification! = UILocalNotification()
    if(notifyAlarm != nil)
    {
        notifyAlarm.fireDate  = notificationTime
        notifyAlarm.timeZone  = NSTimeZone.defaultTimeZone()
        if(withCategory == true)
        {
            notifyAlarm.category  = "FIRST_CATEGORY"
        }
        notifyAlarm.soundName = UILocalNotificationDefaultSoundName
        notifyAlarm.alertBody = message
        app.scheduleLocalNotification(notifyAlarm)
    }
}

在上面的代码中,我尝试将本地通知设置为&#34;提醒&#34;并且&#34;加入servey&#34;。但是,我无法正确设置本地通知时间。

感谢您的回答

祝你好运

1 个答案:

答案 0 :(得分:0)

您只需在设置timeZone后设置fireDate。

notifyAlarm.timeZone = NSTimeZone.localTimeZone()
notifyAlarm.fireDate = notificationTime

此外,您不应将boolean var与true进行比较。这是多余的

if withCategory { 
    notifyAlarm.category  = "FIRST_CATEGORY"
}

您还需要从代码中删除.dateByAddingTimeInterval(3 * 60 * 60)。