I am using cvcalendar and there is in everyday a different times for fajer, dohor , aser , maghreb , ishaa . for example i have selected the Adan for Fajer, so i want to get the adan in everyday and everyday has a different time. so when i get a notification in DidreceivedLocalNotification i want go to next day in calendar and get the time of the next day, knowing that am getting the times from CoreData .
in viewWillappear
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let calendar = NSCalendar.currentCalendar()
let calendarForDate = NSCalendar.currentCalendar()
let componentsForDate = calendar.components([.Day , .Month , .Year], fromDate: date)
let year = componentsForDate.year
let month = componentsForDate.month
let day = componentsForDate.day
//////////
//// Conditions after selecting the user (vibration, beep, Adan ) these conditions are testing the selected choice to send a notification to the user on his choice
//
if prayerCommingFromAdan.id == 0 && prayerCommingFromAdan.ringToneId != 0{
notificationId.id = 0
let hours = prayer0.time[0...1]
let minutes = prayer0.time[3...4]
let fajerTime = "\(month)-\(day)-\(year) \(hours):\(minutes)"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy hh:mm"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
// convert string into date
let dateValue = dateFormatter.dateFromString(fajerTime) as NSDate!
var dateComparisionResult:NSComparisonResult = NSDate().compare(dateValue)
if dateComparisionResult == NSComparisonResult.OrderedAscending
{
addNotificationAlarm(year, month: month, day: day, hour: prayer0.time[0...1], minutes: prayer0.time[3...4], soundId: prayerCommingFromAdan.ringToneId, notificationBody: "It is al fajr adan")
}
What should i do in DidreceivedLocalNotification in AppDelegate?
You can use this code for scheduling your daily notifications according to time.
func ScheduleMorning() {
let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var dateFire=NSDate()
var fireComponents = calendar.components([.Hour, .Minute, .Second], fromDate: dateFire)
if (fireComponents.hour >= 7) {
dateFire=dateFire.dateByAddingTimeInterval(86400) // Use tomorrow's date
fireComponents = calendar.components([.Hour, .Minute, .Second], fromDate: dateFire)
}
fireComponents.hour = 7
fireComponents.minute = 0
fireComponents.second = 0
// Here is the fire time you can change as per your requirement
dateFire = calendar.dateFromComponents(fireComponents)!
let localNotification = UILocalNotification()
localNotification.fireDate = dateFire // Pass your Date here
localNotification.alertBody = "Your Message here."
localNotification.userInfo = ["CustomField1": "w00t"]
localNotification.repeatInterval = NSCalendarUnit.Day
UIApplication.sharedApplication().scheduleLocalNotification(localNotification) }
for receiving
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
// Do something serious in a real app.
print("Received Local Notification:")
print(notification.userInfo)
}
Related
I am trying calculate the age from birthdayDate in Swift with this function:
var calendar : NSCalendar = NSCalendar.currentCalendar()
var dateComponentNow : NSDateComponents = calendar.components(
NSCalendarUnit.CalendarUnitYear,
fromDate: birthday,
toDate: age,
options: 0)
But I get an error Extra argument toDate in call
In objective c this was the code, but I don't know why get this error:
NSDate* birthday = ...;
NSDate* now = [NSDate date];
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit
fromDate:birthday
toDate:now
options:0];
NSInteger age = [ageComponents year];
Is there correct form better than this?
You get an error message because 0 is not a valid value for NSCalendarOptions.
For "no options", use NSCalendarOptions(0) or simply nil:
let ageComponents = calendar.components(.CalendarUnitYear,
fromDate: birthday,
toDate: now,
options: nil)
let age = ageComponents.year
(Specifying nil is possible because NSCalendarOptions conforms to the RawOptionSetType protocol which in turn inherits
from NilLiteralConvertible.)
Update for Swift 2:
let ageComponents = calendar.components(.Year,
fromDate: birthday,
toDate: now,
options: [])
Update for Swift 3:
Assuming that the Swift 3 types Date and Calendar are used:
let now = Date()
let birthday: Date = ...
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
let age = ageComponents.year!
I create this method its very easy just put the birthday date in the method and this will return the Age as a Int
Swift 3
func calcAge(birthday: String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let now = Date()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: [])
let age = calcAge.year
return age!
}
Swift 2
func calcAge(birthday: String) -> Int{
let dateFormater = NSDateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.dateFromString(birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()
let calcAge = calendar.components(.Year, fromDate: birthdayDate!, toDate: now, options: [])
let age = calcAge.year
return age
}
Usage
print(calcAge("06/29/1988"))
For swift 4 works fine
func getAgeFromDOF(date: String) -> (Int,Int,Int) {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "YYYY-MM-dd"
let dateOfBirth = dateFormater.date(from: date)
let calender = Calendar.current
let dateComponent = calender.dateComponents([.year, .month, .day], from:
dateOfBirth!, to: Date())
return (dateComponent.year!, dateComponent.month!, dateComponent.day!)
}
let age = getAgeFromDOF(date: "2000-12-01")
print("\(age.0) Year, \(age.1) Month, \(age.2) Day")
This works for Swift 3
let myDOB = Calendar.current.date(from: DateComponents(year: 1994, month: 9, day: 10))!
let myAge = Calendar.current.dateComponents([.month], from: myDOB, to: Date()).month!
let years = myAge / 12
let months = myAge % 12
print("Age : \(years).\(months)")
This is working in swift 3 for me..
let now = NSDate()
let calendar : NSCalendar = NSCalendar.current as NSCalendar
let ageComponents = calendar.components(.year, from: datePickerView.date, to: now as Date, options: [])
let age = ageComponents.year!
ageCalculated.text = String(age)
Thanks to #Martin R
//Create string extension to make more easy
extension String {
func getDate(format: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.date(from: self) ?? Date()
}
}
Get today's date and your birthday date
let today = Date()
let birthDate = "1990-01-01".getDate(format: "yyyy-MM-dd")
Create an instance of the user's current calendar
let calendar = Calendar.current
Use calendar to get difference between two dates
let components = calendar.dateComponents([.year, .month, .day], from: birthDate, to: today)
let ageYears = components.year //get how many years old
let ageMonths = components.month //extra months
let ageDays = components.day // extra days
This is the best way on swift 5
lazy var dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
let birthday = dateFormatter.date(from: "1980-04-25")
let timeInterval = birthday?.timeIntervalSinceNow
let age = abs(Int(timeInterval! / 31556926.0))
This function gets current time and finds the next time in an array. When the current time is before midday and the next time is after midday, it returns the next time as am when it should be pm.
How can I change this? Would I need to use a 12 hour clock instead of a 24 hour clock?
import UIKit
import Foundation
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute], fromDate: date)
let hour = components.hour
let minutes = components.minute
let currentTime = "\(hour)" + ":" + "\(minutes)" //output 10:47
let timesArray = ["5:45", "6:35", "7:00", "7:30", "7:50", "8:20", "8:40", "9:15", "10:10",
"12:40", "14:15", "14:50", "15:40", "16:10", "17:10", "17:40", "18:40", "19:25", "20:50"]
// create a method to convert your time to minutes
func stringToMinutes(input:String) -> Int {
let components = input.componentsSeparatedByString(":")
let hour = Int((components.first ?? "0")) ?? 0
let minute = Int((components.last ?? "0")) ?? 0
return hour*60 + minute
}
//create an array with the minutes from the original array
let timesMinutesArray:[Int] = timesArray.map { stringToMinutes($0) }
let dayMinute = stringToMinutes(currentTime)
// filter out the times that has already passed
let filteredTimesArray = timesMinutesArray.filter{$0 > dayMinute }
// get the first time in your array
if let firstTime = filteredTimesArray.first {
// find its position and extract it from the original array
let nextDeparture = timesArray[timesMinutesArray.indexOf(firstTime)!] // output "12:40"
let userCalendar = NSCalendar.currentCalendar()
let dateMakerFormatter = NSDateFormatter()
dateMakerFormatter.calendar = userCalendar
dateMakerFormatter.dateFormat = "yyyy/MM/dd"
// How many hours and minutes between current time and next departure?
dateMakerFormatter.dateFormat = "h:mm"
let startTime = dateMakerFormatter.dateFromString(currentTime)!
let endTime = dateMakerFormatter.dateFromString(nextDeparture)! //this comes back as 12:40 am not pm
let hourMinuteComponents: NSCalendarUnit = [.Hour, .Minute]
let timeDifference = userCalendar.components(
hourMinuteComponents,
fromDate: startTime,
toDate: endTime,
options: [])
let difference = (timeDifference.hour*60) + (timeDifference.minute)
}
Try a capital H in your dateFormat:
dateMakerFormatter.dateFormat = "H:mm"
I was facing the struggle of making a timer app, so I thought that now that I solved it I could help others who face the problem. So basically this app counts down to a specific date from the current time. As stack overflow allows a Q and A format I hope that can help you. See the comments for explanations.
Cleaned up and updated with countdown computed on a timer and leading zero String format.
let futureDate: Date = {
var future = DateComponents(
year: 2020,
month: 1,
day: 1,
hour: 0,
minute: 0,
second: 0
)
return Calendar.current.date(from: future)!
}()
var countdown: DateComponents {
return Calendar.current.dateComponents([.day, .hour, .minute, .second], from: Date(), to: futureDate)
}
#objc func updateTime() {
let countdown = self.countdown //only compute once per call
let days = countdown.day!
let hours = countdown.hour!
let minutes = countdown.minute!
let seconds = countdown.second!
countdownLabel.text = String(format: "%02d:%02d:%02d:%02d", days, hours, minutes, seconds)
}
func runCountdown() {
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
Here is the solution of how I managed to create a countdown timer to a specific NSDate, for SO allows Q and A Style Answers.
// here we set the current date
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: date)
let hour = components.hour
let minutes = components.minute
let month = components.month
let year = components.year
let day = components.day
let currentDate = calendar.dateFromComponents(components)
// here we set the due date. When the timer is supposed to finish
let userCalendar = NSCalendar.currentCalendar()
let competitionDate = NSDateComponents()
competitionDate.year = 2015
competitionDate.month = 6
competitionDate.day = 21
competitionDate.hour = 08
competitionDate.minute = 00
let competitionDay = userCalendar.dateFromComponents(competitionDate)!
// Here we compare the two dates
competitionDay.timeIntervalSinceDate(currentDate!)
let dayCalendarUnit: NSCalendarUnit = (.CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute)
//here we change the seconds to hours,minutes and days
let CompetitionDayDifference = userCalendar.components(
dayCalendarUnit, fromDate: currentDate!, toDate: competitionDay,
options: nil)
//finally, here we set the variable to our remaining time
var daysLeft = CompetitionDayDifference.day
var hoursLeft = CompetitionDayDifference.hour
var minutesLeft = CompetitionDayDifference.minute
Hope that helps you guys if you're facing the same struggle as I have
Cleaned up/updated for latest Swift version of the accepted answer.
// here we set the current date
let date = NSDate()
let calendar = Calendar.current
let components = calendar.dateComponents([.hour, .minute, .month, .year, .day], from: date as Date)
let currentDate = calendar.date(from: components)
let userCalendar = Calendar.current
// here we set the due date. When the timer is supposed to finish
let competitionDate = NSDateComponents()
competitionDate.year = 2017
competitionDate.month = 4
competitionDate.day = 16
competitionDate.hour = 00
competitionDate.minute = 00
let competitionDay = userCalendar.date(from: competitionDate as DateComponents)!
//here we change the seconds to hours,minutes and days
let CompetitionDayDifference = calendar.dateComponents([.day, .hour, .minute], from: currentDate!, to: competitionDay)
//finally, here we set the variable to our remaining time
let daysLeft = CompetitionDayDifference.day
let hoursLeft = CompetitionDayDifference.hour
let minutesLeft = CompetitionDayDifference.minute
print("day:", daysLeft ?? "N/A", "hour:", hoursLeft ?? "N/A", "minute:", minutesLeft ?? "N/A")
//Set countdown label text
countDownLabel.text = "\(daysLeft ?? 0) Days, \(hoursLeft ?? 0) Hours, \(minutesLeft ?? 0) Minutes"
This worked for me.
The only thing that troubles me is that it doesn't really countdown as the user has to refresh the page for it to recount. You can see it "counting" when the user is scrolling up and down cells on a UITableView as the cells do refresh the view.
Another thing is that I have on NSTimeZone of the currentDate "GMT+2:00" as it works for my time but only because I haven't figured out how to use the device NSTimeZone yet.
let releaseDate = "2015-05-02'T'22:00:00:000Z"
let futureDateFormatter = NSDateFormatter()
futureDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date: NSDate = futureDateFormatter.dateFromString(releaseDate!)!
let currentDate = NSDate();
let currentFormatter = NSDateFormatter();
currentFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
currentFormatter.timeZone = NSTimeZone(abbreviation: "GMT+2:00")
let diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: currentDate, toDate: date, options: NSCalendarOptions.init(rawValue: 0))
let countdown = "\(diffDateComponents.month) m: \(diffDateComponents.day) d: \(diffDateComponents.hour) h: \(diffDateComponents.minute) min"
I need to schedule a notification. If the date made from the current date date components with the dateFromData time components is early than the current day, I would like to change it to the next day. Here is what I have so far. The date comparison dose not work no matter how I set it. It either always changes it or never changes it.
var dateComps = calendar.components(NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit | NSCalendarUnit.HourCalendarUnit | NSCalendarUnit.MinuteCalendarUnit, fromDate: NSDate())
dateComps.hour = calendar.component(NSCalendarUnit.HourCalendarUnit, fromDate: dateFromData)
dateComps.minute = calendar.component(NSCalendarUnit.MinuteCalendarUnit, fromDate: dateFromData)
if fireDate.compare(NSDate()) == NSComparisonResult.OrderedDescending {
//change day to next day
dateComps.day += 1
println("Change day")
}else{
println("Do not change day")
}
let notifactionOfAmountOfWork = UILocalNotification()
notifactionOfAmountOfWork.category = "normalNotifactionCatagory"
notifactionOfAmountOfWork.fireDate = calendar.dateFromComponents(dateComps)
How your firstDate defined? The following program works, I just tried it. You could change comps1.day and comps2.day to let it hit both conditions.
import UIKit
let calendar1 = NSCalendar.currentCalendar()
let comps1 = NSDateComponents()
comps1.day = 7
let date1 = calendar1.dateByAddingComponents(comps1, toDate: NSDate(), options: NSCalendarOptions.allZeros)
let calendar2 = NSCalendar.currentCalendar()
let comps2 = NSDateComponents()
comps2.day = 0
let date2 = calendar2.dateByAddingComponents(comps2, toDate: NSDate(), options: NSCalendarOptions.allZeros)
if date1?.compare(date2!) == NSComparisonResult.OrderedDescending
{
println("date1 is after date 2")
}else{
println("date1 is before date 2")
}
I am trying calculate the age from birthdayDate in Swift with this function:
var calendar : NSCalendar = NSCalendar.currentCalendar()
var dateComponentNow : NSDateComponents = calendar.components(
NSCalendarUnit.CalendarUnitYear,
fromDate: birthday,
toDate: age,
options: 0)
But I get an error Extra argument toDate in call
In objective c this was the code, but I don't know why get this error:
NSDate* birthday = ...;
NSDate* now = [NSDate date];
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit
fromDate:birthday
toDate:now
options:0];
NSInteger age = [ageComponents year];
Is there correct form better than this?
You get an error message because 0 is not a valid value for NSCalendarOptions.
For "no options", use NSCalendarOptions(0) or simply nil:
let ageComponents = calendar.components(.CalendarUnitYear,
fromDate: birthday,
toDate: now,
options: nil)
let age = ageComponents.year
(Specifying nil is possible because NSCalendarOptions conforms to the RawOptionSetType protocol which in turn inherits
from NilLiteralConvertible.)
Update for Swift 2:
let ageComponents = calendar.components(.Year,
fromDate: birthday,
toDate: now,
options: [])
Update for Swift 3:
Assuming that the Swift 3 types Date and Calendar are used:
let now = Date()
let birthday: Date = ...
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
let age = ageComponents.year!
I create this method its very easy just put the birthday date in the method and this will return the Age as a Int
Swift 3
func calcAge(birthday: String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let now = Date()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: [])
let age = calcAge.year
return age!
}
Swift 2
func calcAge(birthday: String) -> Int{
let dateFormater = NSDateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.dateFromString(birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()
let calcAge = calendar.components(.Year, fromDate: birthdayDate!, toDate: now, options: [])
let age = calcAge.year
return age
}
Usage
print(calcAge("06/29/1988"))
For swift 4 works fine
func getAgeFromDOF(date: String) -> (Int,Int,Int) {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "YYYY-MM-dd"
let dateOfBirth = dateFormater.date(from: date)
let calender = Calendar.current
let dateComponent = calender.dateComponents([.year, .month, .day], from:
dateOfBirth!, to: Date())
return (dateComponent.year!, dateComponent.month!, dateComponent.day!)
}
let age = getAgeFromDOF(date: "2000-12-01")
print("\(age.0) Year, \(age.1) Month, \(age.2) Day")
This works for Swift 3
let myDOB = Calendar.current.date(from: DateComponents(year: 1994, month: 9, day: 10))!
let myAge = Calendar.current.dateComponents([.month], from: myDOB, to: Date()).month!
let years = myAge / 12
let months = myAge % 12
print("Age : \(years).\(months)")
This is working in swift 3 for me..
let now = NSDate()
let calendar : NSCalendar = NSCalendar.current as NSCalendar
let ageComponents = calendar.components(.year, from: datePickerView.date, to: now as Date, options: [])
let age = ageComponents.year!
ageCalculated.text = String(age)
Thanks to #Martin R
//Create string extension to make more easy
extension String {
func getDate(format: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.date(from: self) ?? Date()
}
}
Get today's date and your birthday date
let today = Date()
let birthDate = "1990-01-01".getDate(format: "yyyy-MM-dd")
Create an instance of the user's current calendar
let calendar = Calendar.current
Use calendar to get difference between two dates
let components = calendar.dateComponents([.year, .month, .day], from: birthDate, to: today)
let ageYears = components.year //get how many years old
let ageMonths = components.month //extra months
let ageDays = components.day // extra days
This is the best way on swift 5
lazy var dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
let birthday = dateFormatter.date(from: "1980-04-25")
let timeInterval = birthday?.timeIntervalSinceNow
let age = abs(Int(timeInterval! / 31556926.0))