Date Picker Now. Cocoa-OSX Swift - macos

How can I make the date picker show the date and time that is now? Without clicking nothing, just at the beginning. I am very new in Cocoa, I would appreciate any orientation.
This is what I have done:
- I create a new project > OSX > Application > Cocoa Application
- Main.storyboard. Drag a Date Picker
- Ctrl + drag from date picker to ViewController.swift. I give it the name datePicker: #IBOutlet weak var datePicker: NSDatePicker!

Add [datePicker setDateValue:[NSDate new]]; in viewdidLoad of View Controller

Here is a function that returns the hour and the day and corrects for different time zones, I am using 7 for Nevada PST time zone but you can update for your specific state
func returnHourDay() -> (Int, Int) {
let dateNow = Date()
let calendar = Calendar.current
var Hour = (calendar as NSCalendar).component(NSCalendar.Unit.hour, from: dateNow)
let Day = (calendar as NSCalendar).component(NSCalendar.Unit.weekday, from: dateNow)
//correct for specific time zones
func ltzOffset() -> Int { return NSTimeZone.local.secondsFromGMT() }
let hourOffset = 7 + ltzOffset()/60/60 //0 for Nevada 7 - 7 = 0
Hour = Hour+hourOffset
return (Hour, Day)
}

Related

Datepicker values only change when changing date

Is it possible to have datepicker land on todays date when the app starts?
currently my app shows no values on start up and only when I start changing the date in my datepicker then values start appearing. datepicker outputs values to labels
Which programming language do you use?
This code is for swift3 ;
You should write it in viewDidLoad()
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
yourTextField.text = dateFormatter.string(from: (NSDate() as Date))

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

Photo changing every day(Xcode, Swift)

I haven't write code for this But I want some help that can it be possible to code so that it shows new photo everyday. for example I have 10 images and I want to display each image for like September 16,17,18, and so on ?
Here you go...
Call method getImageForToday() where ever you want to fetch image for today (This solution will work specific to your case, i.e. as you mentioned you have 10 images)
func getImageForToday() -> UIImage
{
let arrImages = ["image1.png", "image2.png" ... "image10.png"]
var imageName = arrImages[getLastCharacterFromTodayDate()]
return UIImage(named: imageName)
}
func getLastCharacterFromTodayDate() -> Int
{
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let component = calendar.components(NSCalendarUnit.CalendarUnitDay, fromDate: NSDate())
return component.day % 10
}
You can use the object NSDate to know what day is it and after that doing something.
First you have your dictionnary of image like that :
let images = [ UIImage(named: "image1.png")!, UIImage(named: "image2.png")!, UIImage(named: "image3.png")]
so now, you must know what day is it for the first app openning in exemple.
So you can do that :
let date = NSDate()
You put the element date in UserDefaults. (in order to save it)
You can now display a image. You make a random number and you take UIImage at this random position.
The day after, or the next app opening you recheck the NSDate with the NSDate saved and if it's different you take a other photo.

kendo datepicker - set date without looking maxdate

I have one kind of scenario using date picker. I have date picker with max date=current date + 10 days,on page load only i want to show date more than the max date,but I'm allowing user to enter only up to max date. Is it possible. Without looking maxing date i want to display only the date what ever i want.code:-
var datepicker = $("#date" + uid).data("kendoDatePicker");
var addDays = new Date();
if (arr[1] == "") {
var d = new Date();
datepicker.min(new Date());
datepicker.max(new Date(d.getDate() , d.getMonth(), d.getDate()+ parseInt(arr[1]) - parseInt(1)));
}
I don't know if this is achievable. But what if you try to add two date pickers instead? One that display only the text, and the other only the calendar button. You need to play a bit the CSS, but I think it could spare you a lot of time.

Replacing NSDate value if two NSDate objects aren't equal

basically I'm writing an app and I want some of its values to update weekly - so, using NSDate and NSUserDefaults I currently have this scenario set out:
let userDefaults = NSUserDefaults.standardUserDefaults()
var startOfWeek: NSDate?
The above is global^
var referenceDate = NSDate.timeIntervalSinceReferenceDate()
while referenceDate > 604800 {
if referenceDate > 604800 {
referenceDate -= 604800
}
This basically takes the amount of seconds that have elapsed since the 1st of Jan 2001 and subtracts 604800, which is the amount of seconds in a week, until you have an amount of seconds that is less than a week. This amount of seconds is basically the amount of seconds into the week, you're in.
After this I then create a variable which is just the negative of how many seconds into the week we are, a variable which is the current time and use them to create a new date object which is the start point for the week:
var weekTimer: NSTimeInterval = (-referenceDate)
var startOfWeek = userDefaults.objectForKey("startOfWeekKey") as? NSDate
var currentTime = NSDate(timeIntervalSinceNow: 0)
if startOfWeek == nil {
startOfWeek = NSDate(timeInterval: weekTimer, sinceDate: currentTime)
userDefaults.objectForKey("startOfWeekKey")
}
else {
}
So basically it creates a value for the start of the week and saves it to NSUserDefaults under the key "startOfWeekKey" if the value doesn't already exist. If the value does already exist, because it's already been saved, it's happy with this value and nothing happens.
Now, we create a new value to compare to our startOfWeek value so we can test if we enter a new week.
var startOfWeekCheck = NSDate(timeInterval: weekTimer sinceDate: currentTime)
Now we compare them:
if startOfWeek! == startOfWeekCheck {
}
else {
println("New week begins") //update other, irrelevant stuff here
startOfWeek = startOfWeekCheck
}
No matter what, new week begins is always printed, I added the following line to check what was happening:
println("\(startOfWeek!) \(startOfWeekCheck)")
And it prints the same value to the logs
I'm pretty unsure what to do at this point. Did I mess up? Can you not compare the two date objects like that? Is this a ridicuously inefficient manner to create a way to reset/change something once a week?
Note, this is not the exact code, I typed this all by hand because the code is on my macbook and I'm on my desktop, so if there are any typos / w/e don't worry about it, no compile errors on my mac.
Thanks!
This looks way too complicated. There is no need to do all the date calculations yourself. Especially because you do them wrong. Not every week has 604800 seconds. In many timezones you have one week per year which has 601200 seconds, and one week which has 608400 seconds. Also known as Daylight saving time. There are even countries that skipped a whole day in one year.
You have to use NSCalendar and NSDateComponents for correct date calculations.
But I would do it completely different:
Save the next refresh date in NSUserDefaults (default to distantPast)
If today >= next refresh date: refresh & write new refresh date.
Something like this:
let calendar = NSCalendar.currentCalendar()
// If nextRefreshDate was never written by us (i.e. first start of app) it will containt distantPast, which is in year 1 or so
NSUserDefaults.standardUserDefaults().registerDefaults(["nextRefreshDate" : NSDate.distantPast()])
// since we registered a default value we will always receive a valid NSDate object, so we can force unwrap
let nextRefreshDate = NSUserDefaults.standardUserDefaults().objectForKey("nextRefreshDate") as NSDate
// equivalent to: (nextRefreshDate < today) || (nextRefreshDate == today)
if nextRefreshDate.compare(NSDate()) != NSComparisonResult.OrderedDescending {
println("Refresh")
let refreshSuccess = true // get from your internet download code
if refreshSuccess {
// don't save the next refresh date until the refresh was actually sucessful. This makes sure that we refresh on next launch if this refresh fails for some reason
var startOfCurrentWeek: NSDate?
if calendar.rangeOfUnit(.CalendarUnitWeekOfMonth, startDate: &startOfCurrentWeek, interval: nil, forDate: NSDate()) {
if let startOfCurrentWeek = startOfCurrentWeek {
if let startOfNextWeek = calendar.dateByAddingUnit(.CalendarUnitWeekOfMonth, value: 1, toDate: startOfCurrentWeek, options: nil) {
NSUserDefaults.standardUserDefaults().setObject(startOfNextWeek, forKey: "nextRefreshDate")
println("Next refresh scheduled for \(startOfNextWeek)")
}
}
}
}
}
else {
println("No refresh necessary. Next refresh scheduled for \(nextRefreshDate)")
}

Resources