How to get weekends vs weekdays in Cocoa? - cocoa

What is the correct calendar-agnostic way (in either iOS or OS X) to get standard business days of the week (e.g. weekdays) versus non-working days of the week? This is taking into account that some parts of the world doesn't follow the Monday through Friday working day routine. E.g. the UAE and some parts of Malaysia works from Sunday through Thursday.
I'm looking to emulate iOS' built-in Alarm application in which if I select a repeating day of Monday through Friday, it will say that my alarm repeats "Weekdays" whereas for alarms that fires on Saturday and Sunday says "Weekends". However, I'd like my app to also work correctly in other parts of the world that doesn't follow the western world's work week.
I've been toying around with NSCalendar's isDateInWeekend function with various other calendars and haven't been able to find a good method to determine weekday vs weekend. Here's a snippet from a Swift playground that I got so far:
import UIKit
let arabicLocale = NSLocale(localeIdentifier: "en_AR")
let islamicTabularCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierIslamicTabular)
islamicTabularCalendar?.locale = arabicLocale
let islamicTabularFormatter = NSDateFormatter()
islamicTabularFormatter.calendar = islamicTabularCalendar
islamicTabularFormatter.dateStyle = NSDateFormatterStyle.FullStyle
let gregorianCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
gregorianCalendar?.locale = arabicLocale
let gregorianFormatter = NSDateFormatter()
gregorianFormatter.calendar = gregorianCalendar
gregorianFormatter.dateStyle = NSDateFormatterStyle.FullStyle
let monday = NSDateComponents()
monday.weekday = 2
monday.weekOfMonth = 0
let friday = NSDateComponents()
friday.weekday = 6
friday.weekOfMonth = 0
let mondayDate = islamicTabularCalendar?.dateFromComponents(monday)
gregorianFormatter.stringFromDate(mondayDate!) // "Monday, July 8, 622"
islamicTabularFormatter.stringFromDate(mondayDate!) // "Monday, Dhuʻl-Hijjah 20, 0 AH"
islamicTabularCalendar?.isDateInWeekend(mondayDate!) // false
let fridayDate = islamicTabularCalendar?.dateFromComponents(friday)
gregorianFormatter.stringFromDate(fridayDate!) // Friday, July 12, 622
islamicTabularFormatter.stringFromDate(fridayDate!) // Friday, Dhuʻl-Hijjah 24, 0 AH
islamicTabularCalendar?.isDateInWeekend(fridayDate!) // false
What I'm looking for is something that returns false for Fridays in parts of the world that practices Monday-Friday working days but returns true for UAE and the like.

I finally got it. The mistake was in the locale identifier which should be en_AE instead of en_AR
import UIKit
let arabicLocale = NSLocale(localeIdentifier: "en_AE")
let islamicTabularCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierIslamicTabular)
islamicTabularCalendar?.locale = arabicLocale
let islamicTabularFormatter = NSDateFormatter()
islamicTabularFormatter.calendar = islamicTabularCalendar
islamicTabularFormatter.dateStyle = NSDateFormatterStyle.FullStyle
let gregorianCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
gregorianCalendar?.locale = arabicLocale
let gregorianFormatter = NSDateFormatter()
gregorianFormatter.calendar = gregorianCalendar
gregorianFormatter.dateStyle = NSDateFormatterStyle.FullStyle
let monday = NSDateComponents()
monday.weekday = 2
monday.weekOfMonth = 0
let friday = NSDateComponents()
friday.weekday = 6
friday.weekOfMonth = 0
let mondayDate = islamicTabularCalendar?.dateFromComponents(monday)
gregorianFormatter.stringFromDate(mondayDate!) // "Monday, July 8, 622"
islamicTabularFormatter.stringFromDate(mondayDate!) // "Monday, Dhuʻl-Hijjah 20, 0 AH"
islamicTabularCalendar?.isDateInWeekend(mondayDate!) // false
gregorianCalendar?.isDateInWeekend(mondayDate!) // false
let fridayDate = islamicTabularCalendar?.dateFromComponents(friday)
gregorianFormatter.stringFromDate(fridayDate!) // Friday, July 12, 622
islamicTabularFormatter.stringFromDate(fridayDate!) // Friday, Dhuʻl-Hijjah 24, 0 AH
islamicTabularCalendar?.isDateInWeekend(fridayDate!) // true
gregorianCalendar?.isDateInWeekend(fridayDate!) // false

Related

AMCharts - unable to get Line graph to draw

I have a line graph drawing using data created like so:
for (var i = 1; i < 366; i++) {
visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
data.push({ date: new Date(2018, 0, i), value: visits });
}
The rest of the options set look like:
__this._chart.data = data;
var dateAxis = __this._chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
dateAxis.renderer.axisFills.template.disabled = true;
dateAxis.renderer.ticks.template.disabled = true;
var valueAxis = __this._chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.tooltip.disabled = true;
valueAxis.renderer.minWidth = 35;
valueAxis.renderer.axisFills.template.disabled = true;
valueAxis.renderer.ticks.template.disabled = true;
var series = __this._chart.series.push(new am4charts.LineSeries());
series.dataFields.dateX = "date";
series.dataFields.valueY = "value";
This draws a random line for the whole year and it works.
We dont want to show every day, we want to show monthly data. So I have data that when processed shows up in the form:
{
category: Mon Oct 31 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
column-1: 50
}
Theres only 9 of them and they cover up to January 2019, so there would be huge gaps between the data points. the object name of category is different to date but I set the series' dateX = "category".
So my question is, can the line graph be used to do monthly data where there could be gaps in the data?
If so, how do I get it to work? I use the rest of the options the exact same as the test that is working, except for hte changed values of series' dateX and valueY.

Swift 3 Local Notifications - Setting Automatic Timezone

So this worked flawlessly in Swift 2 but in Swift 3 it has problems:
func myNotifications () {
let interval = 2.0
var daysOut = 2.0
let myArray =getArray()
for i in 0..<myArray.count {
let message = ("\(myArray[i])\n-\(myArray[i])")
let localNotification = UILocalNotification()
localNotification.fireDate = Date(timeIntervalSinceNow: (60*60*24*daysOut))
localNotification.alertBody = message
localNotification.timeZone = NSTimeZone.autoupdatingCurrent
localNotification.category = "Message"
UIApplication.shared.scheduleLocalNotification(localNotification)
daysOut += interval
}
let arrayCount = Double(myArray.count)
let lastNotif_Date = Date(timeIntervalSinceNow: (60*60*24*interval*(quoteCount+1)))
userPref_NSDefault.set(lastNotif_Date, forKey: "notification_EndDate")
}
Specifically, this line no longer works which is a big deal because I have users in multiple timezones and I want to make sure this works:
localNotification.timeZone = NSTimeZone.autoupdatingCurrent
I get the error message:
Type "NSTimeZone" has no member "autoUpdatingCurrent"
Any ideas? I tried "timeZone.automatic", ".automatic", and some other variations but haven't been able to figure it out.
autoupdatingCurrent != autoupdatingCurrent
NSTimeZone has been renamed to TimeZone

Swift: (Countdown app) How to make date picker choose the due date?

Making a countdown app and instead of manually adding the due date i want to be able to do it with a date picker.
Here is the code i am using now. What i need help with is implementing code that let's me do this by using the date picker (The competitionDate).
// Here we set the current date
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute, .Second, .Nanosecond], 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
// final Calendar value
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 = calendar.components([NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: date)
you mean to get the date of the date picker?
you can do it like so:
let date:NSDate = datePicker.date

Spritekit Swift particle SKEmitterNode add remove

so this is nice for create a particle, but whats the right way to remove it , after the duration, sparkEmmiter.particleLifetime do not remove it automatically
let sparkEmmiter = SKEmitterNode(fileNamed: "MyParticle.sks")
sparkEmmiter.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2 - 200)
sparkEmmiter.name = "sparkEmmitter"
sparkEmmiter.zPosition = 1
sparkEmmiter.targetNode = self
sparkEmmiter.particleLifetime = 1
self.addChild(sparkEmmiter)
this solutions produce simulator crash
var re = SKAction.waitForDuration(1)
var remove = SKAction.removeFromParent()
var seq = SKAction.sequence([re , remove])
sparkEmmiter.runAction(seq)

how to find time difference in titanium

I am new to titanium.
I want to find time difference in titanium. Ex 12.00 AM- 12.00 PM should give me 12 hours.
But I'm not able to get how to find it in titanium.
I'm trying
function calculatetime(chkintime,chkouttime)
{
var difference = chkintime - chkouttime;
Ti.API.info(':'+difference);
var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60
Ti.API.info(':'+hoursDifference);
Ti.API.info(':'+minutesDifference);
var time=hoursDifference+':'+minutesDifference;
return time;
}
It sometimes gives correct answer while sometimes negative values.
here chkintime and chkouttime values are in miliseconds e.g. 1355495784321
It's no different from finding a time difference in JavaScript. (In fact, it is finding a time difference in JavaScript.)
Check time difference in Javascript
Past that, a nice way to calculate the number of days between X and Y is to find out the MS difference, then add that time to a set date, like January 1st, 2000. Then you can really easily pull the number of years, months, days, hours, minutes, and seconds. There will be some inaccuracy caused by leap years, but if you're dealing with small period, it doesn't matter at all.
var start = new Date('February, 22, 2011 2:00 PM');
var end = new Date('February, 22, 2011 4:00 PM');
var ms = end - start;
var niceDate = new Date(new Date('January 1, 2000').getTime() + ms);
var years = niceDate.getFullYear() - 2000;
var months = niceDate.getMonth();
var days = niceDate.getDate();
var hours = niceDate.getHours();
var minutes = niceDate.getMinutes();
var seconds = niceDate.getSeconds();
alert(years + ' years,\n'
+ months + ' months,\n'
+ days + ' days,\n'
+ hours + ' hours,\n'
+ minutes + ' min,\n'
+ seconds + ' sec');

Resources