I have a daily notification that reminds the user to use the app. I would like the text to not be static though. I have say, 5 different strings, and I would like the string to be chosen randomly if possible.
My current code, that uses the same text everyday:
let date: NSDate = NSDate()
let cal: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
let newDate: NSDate = cal.dateBySettingHour(22, minute: 00, second: 0, ofDate: date, options: NSCalendarOptions())!
var localNotification: UILocalNotification = UILocalNotification()
localNotification.alertAction = "MyApp"
localNotification.alertBody = "Call to action text"
localNotification.fireDate = newDate
localNotification.repeatInterval = NSCalendarUnit.CalendarUnitDay
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
You could use a switch statement based on the day of the week. Here's an excellent NSHipster tutorial on NSDate components. Here's some sample code re: how to pull a day of the week out of an NSDate:
func getDayOfWeek(today:String)->Int {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let todayDate = formatter.dateFromString(today)!
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components(.CalendarUnitWeekday, fromDate: todayDate)
let weekDay = myComponents.weekday
return weekDay
}
let weekday = getDayOfWeek("2014-08-27")
println(weekday) // 4 = Wednesday
Here's Apple's documentation for switch statements.
Basically, you'll want to create a method that takes an NSDate as an input and spits out a day of the week. Once you've got the day of the week, you you can create your custom message in the switch statement.
Related
I am working on get start and end date from today’s date.
I am getting start and end date of current month by using
formula given by Martin R
Get first and last day of month
It is working perfectly.
My issue is how to put my custom value in this line
let components1 = calendar.components([.Year, .Month], fromDate: date)
Can I replace my custom month value to this code?
My requirement is:
I have one tableView for months like January, etc.
When I will click TableView I am getting current month according to tableview.
Suppose I click on January, I will get value 1.
So how to get start and end date of month using my custom month value?
My Code
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MM yyyy"
//To Get Start Date of Month
let components1 = calendar.components([.Year,.Day], fromDate: date)
components1.month = 3
let startOfMonth = calendar.dateFromComponents(components1)!
txtStartDate.text = dateFormatter.stringFromDate(startOfMonth)
try this code:
let calendar = NSCalendar.currentCalendar()
let date = "January 2016" // custom value
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM yyyy"
let components = calendar.components([.Year, .Month, .Day], fromDate: dateFormatter.dateFromString(date)!)
let startOfMonth = calendar.dateFromComponents(components)!
dateFormatter.dateFormat = "MM"
print(dateFormatter.stringFromDate(startOfMonth))
//NSLog("%# : %#", startOfMonth,dateFormatter.stringFromDate(startOfMonth));
Output:
01
I am answering my own question
temp number is month number like if January it will considered as 1.
plz go through this solution to get start and end date from custom values
thanks #Martin R
let calendar = NSCalendar.currentCalendar()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MM yyyy"
//To Get Start Date of Month
let components1 = calendar.components([.Year], fromDate: NSDate())
components1.month = Int(tempNumber!)!
let startOfMonth = calendar.dateFromComponents(components1)!
txtStartDate.text = dateFormatter.stringFromDate(startOfMonth)
//To Get End Date of Month
let comps2 = NSDateComponents()
comps2.month = 1
comps2.day = -1
let endOfMonth = calendar.dateByAddingComponents(comps2, toDate: startOfMonth, options: [])!
txtEndDate.text = dateFormatter.stringFromDate(endOfMonth)
I am trying to schedule a local notification so it will occur at 9:00pm and repeat once a week. I have the following code and I keep receiving a error that says "Cannot assign value of type NSDateComponents to .fireDate. I understand .fireDate will only accept NSDate types but. I can not figure out a way to set the hour variable and minute variable for a NSDate type because I don't think it is possible to do this.
func Notification(){
let dateComponents = NSDateComponents()
dateComponents.day = 4
dateComponents.month = 7
dateComponents.year = 2016
dateComponents.hour = 21
dateComponents.minute = 00
let Notification = UILocalNotification()
Notification.alertAction = "Go Back To App"
Notification.alertBody = "Did you complete your HH and QC?"
Notification.repeatInterval = NSCalendarUnit.WeekOfYear
Notification.timeZone = NSTimeZone.defaultTimeZone()
Notification.fireDate = dateComponents
UIApplication.sharedApplication().scheduleLocalNotification(Notification)
}
Here is how you do it.
Fully Tested on Swift 2.0
//Note I have taken date time from date picker
func scheduleLocalNotification() {
let localNotification = UILocalNotification()
localNotification.fireDate = fixNotificationDate(datePicker.date)
localNotification.alertBody = "Hey, you must go shopping, remember?"
localNotification.alertAction = "View List" // Change depending on your action
localNotification.category = "reminderCategory"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
//This function will help you in generating fire date.
func fixNotificationDate(dateToFix: NSDate) -> NSDate {
let dateComponets: NSDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: dateToFix)
dateComponets.second = 0
let fixedDate: NSDate! = NSCalendar.currentCalendar().dateFromComponents(dateComponets)
return fixedDate
}
Don't forget to request permission for push notification.
Link to my project i worked on
https://drive.google.com/open?id=0B2csGr9uKp1DR0ViZFZMMEZSdms
You should get date from date components like this:
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = NSTimeZone.localTimeZone()
calendar.locale = NSLocale.currentLocale()
let date = calendar.dateFromComponents(dateComponents)!
Notification.fireDate = date
i have a module in that i have 7 buttons all the 7 buttons indicates date for action, i.e first button has current date, second button has tomorrow date, third button has day after tomorrow date likes go on till 7th button, i implemented code from one post to get info like that, but my problem is i can't convert date into string, i need to remove and replace the output value and send it to server
here my sample code :
func addDaystoGivenDate(baseDate:NSDate,NumberOfDaysToAdd:Int)->NSDate
{
let dateComponents = NSDateComponents()
let CurrentCalendar = NSCalendar.currentCalendar()
let CalendarOption = NSCalendarOptions()
dateComponents.day = NumberOfDaysToAdd
let newDate = CurrentCalendar.dateByAddingComponents(dateComponents, toDate: baseDate, options: CalendarOption)
return newDate!
}
override func viewDidLoad() {
let newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 1)
print(newDate)
}
my output is : 2016-04-06 08:35:59 +0000
but my expected output is : 06/04
can anyone solve my issues
You should be able to format your date right with this:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM"
let dateStr = dateFormatter.stringFromDate(newDate!)
// dateStr now contains the string "06/04"
Swift 3.0:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM"
let dateStr = dateFormatter.string(from: newDate)
I have made a functioning app and part of it includes formatting the date from a date picker.
I need to change the first day of the week as the week days are being displayed as "1" - "7". However, day 1 is currently Sunday and I need day 1 to be Monday and Sunday as day 7.
The code for my date formatter and picker are below:
var chosenDate = self.datePicker.date
var formatter = NSDateFormatter()
formatter.dateFormat = "ewYY"
let day = formatter.stringFromDate(chosenDate)
let dateResult = "\(day)"
DestViewController.date = dateResult
I got all of my date formatting info from this page:
http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
I just can't seem to work out how to change this first day of the week?
Many thanks in advance
Mark.
Here is good example in how to manipulate date in swift. you can change the code to fit it better for what you may need, but right now it does what you need.
// Playground - noun: a place where people can play
// Setup the calendar object
let calendar = NSCalendar.currentCalendar()
// Set up date object
let date = NSDate()
// Create an NSDate for the first and last day of the month
let components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth, fromDate: date)
components.month
// Getting the First and Last date of the month
components.day = 1
let firstDateOfMonth: NSDate = calendar.dateFromComponents(components)!
components.month += 1
components.day = 0
let lastDateOfMonth: NSDate = calendar.dateFromComponents(components)!
var unitFlags = NSCalendarUnit.WeekOfMonthCalendarUnit |
NSCalendarUnit.WeekdayCalendarUnit |
NSCalendarUnit.CalendarUnitDay
let firstDateComponents = calendar.components(unitFlags, fromDate: firstDateOfMonth)
let lastDateComponents = calendar.components(unitFlags, fromDate: lastDateOfMonth)
// Sun = 1, Sat = 7
let firstWeek = firstDateComponents.weekOfMonth
let lastWeek = lastDateComponents.weekOfMonth
let numOfDatesToPrepend = firstDateComponents.weekday - 1
let numOfDatesToAppend = 7 - lastDateComponents.weekday + (6 - lastDateComponents.weekOfMonth) * 7
let startDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -numOfDatesToPrepend, toDate: firstDateOfMonth, options: nil)!
let endDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: numOfDatesToAppend, toDate: lastDateOfMonth, options: nil)!
Array(map(0..<42) {
calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: $0, toDate: startDate, options: nil)!
})
"\(components.year)"
//var dateString = stringFromDate(NSDate())// change to your date format
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EE"
var dateString = dateFormatter.stringFromDate(NSDate())
var xdate = dateFormatter.dateFromString(dateString)
//var someDate = dateFormatter.dateString
println(dateString)
this will output::
"Thu"
I'm making an alarm clock where it will tell you how many hours and minutes of sleep you get. I set up a UIDatePicker where the user chooses what time they wanna wake up. It also tells the exact time to the very second. The part that I'm stuck on is how many hours of sleep they are going to get. I tried just basically subtracting the exact time from the UIDatePicker. This worked if they were both in the AM. For example if the user wanted to wake up at 10:30 AM and it is 9:30 AM all you have to do is subtract 10:30 from 9:30 to get 1 hour. I soon realized this wouldn't work if they were different time of days e.g. AM or PM.
How I got the time from UIDatePicker
func handler(sender: UIDatePicker) {
var timeFormatter = NSDateFormatter()
timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var strDate = timeFormatter.stringFromDate(theDatePicker.date)
}
theDatePicker.addTarget(self, action: Selector("handler:"), forControlEvents: UIControlEvents.ValueChanged)
How I got the exact time
var date = NSDate()
var outputFormat = NSDateFormatter()
outputFormat.locale = NSLocale(localeIdentifier:"en_US")
outputFormat.dateFormat = "HH:mm:ss"
timeLabel.text = (outputFormat.stringFromDate(date))
var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("getTime"), userInfo: nil, repeats: true)
My Question:
How do I subtract the UIDatePicker from the exact time to get the hours of sleep the user is getting?
You can use NSCalendar method components:fromDate:toDate:options:, for example:
#IBAction func valueChangedForPicker(sender: UIDatePicker) {
let now = NSDate()
let wakeUpTime = sender.date
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.HourCalendarUnit | .MinuteCalendarUnit | .SecondCalendarUnit, fromDate: now, toDate: wakeUpTime, options: nil)
println(String(format: "%02d:%02d:%02d", components.hour, components.minute, components.second))
}
If you're getting negative values, that's because fromDate is not before toDate. In this case, if you're dealing with a NSDatePicker with time only, you might want to adjust the time of the wakeUpTime to make sure it is in the future.
var wakeUpTime = datePicker.date
if wakeUpTime.compare(now) == .OrderedAscending {
wakeUpTime = calendar.dateByAddingUnit(.DayCalendarUnit, value: 1, toDate: wakeUpTime, options: nil)!
}
Here is an example from a Swift playground:
// Setting up a date since I don't have a UIDatePicker
let dateString = "2014-11-12 07:25"
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm"
var wakeupTime: NSDate = dateFormatter.dateFromString(dateString)!
// var wakeupTime: NSDate = theDatePicker.date
let fromDate = NSDate()
let gregorianCalendar: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
let flags: NSCalendarUnit = .HourCalendarUnit | .MinuteCalendarUnit
let components = gregorianCalendar.components(flags, fromDate: fromDate, toDate: wakeupTime, options: NSCalendarOptions(0))
println("\(components.hour) hours, \(components.minute) minutes")