How do you display real time, time on UIView - Swift - ios

I'm trying to make a alarm clock app but I don't know how to display the time in real time. Would I have to do that programmatically or using an object like UIDatePicker? I have tried searching for it but it is all for Objective-C which I am not at all familiar with.
If you have any questions please comment them down below.

var date = NSDate()
var outputFormat = NSDateFormatter()
outputFormat.locale = NSLocale(localeIdentifier:"en_US")
outputFormat.dateFormat = "HH:mm:ss"
println(outputFormat.stringFromDate(date))

Related

Still confused on Swift DateFormatter & .dateFormat efficiency

I understand that in iOS/Swift creating DateFormatters and setting .dateFormats are expensive, I've read a bunch of different takes here on SO and in blogs, but am still unsure of the best way to efficiently deal with DateFormatter and .dateFormat. Specifically I'm working with an app that roughly mimics Apple's iPhone Weather app UI. Dates arrive via API in timeIntervalSince1970/Unix format. On each view controller I'll use one .dateFormat for the current weather e.g. "EEEE, MMM dd, y", another for formatting date in each of 7 cell in the daily weather table view e.g. "EEEE", and another for the hour in 24 cells in a horizontally scrolling collection view e.g. "ha". Users also page through various view controllers for each location they've saved. I haven't noticed much of a performance hit, but I'd really like to ensure I'm being most efficient, and properly thinking this through (e.g. is Singleton the way to go?).
I had created a Singleton with a single DateFormatter as a static variable, and also created a function to set the .dateFormat and .timeZone for the date formatter (see below). I've assumed based on prior reading that if I stick to iOS 10 or later I don't have to worry about thread safety & that it's likely not a concern in this kind of app, anyway.
class Formatter {
static var dateFormatter = DateFormatter()
private init() {}
static func formatTimeForTimeZone(unixDate: TimeInterval, formatString: String, timeZone: String) -> String {
let usableDate = Date(timeIntervalSince1970: unixDate)
self.dateFormatter.dateFormat = formatString
self.dateFormatter.timeZone = TimeZone(identifier: timeZone)
let dateString = self.dateFormatter.string(from: usableDate)
return dateString
}
}
Each time I'd need to set the date in a view or custom cell class, I'd just call the function, passing in appropriate values like this:
let dateString = Formatter.formatTimeForTimeZone(unixDate: someTime, formatString: someFormatString, timeZone: someTimeZone)
Is it correct that this approach doesn't save me much because I'm setting a .formatString at each call (in each cell)? If so, is there a more sound approach? Advanced thanks for setting me straight.
EDITED FOR BETTER ANSWER:
Thanks Leo for setting me straight & offering suggestions.
After reviewing options & trying out a few things, the solution I ended up using was creating a private global data formatter with class-specific dateFormat String on top of each class that needed a dateFormatter. Being global gives persistence, so I'm not re-creating the DateFormatter or setting .dateFormat String (all allegedy expensive). The global is below, with only change class-to-class being the .dateFormat String
private let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM dd, y"
return dateFormatter
}()
I then created an extension of TimeInterval that handled the formatting that I needed, taking an IANA Time Zone String and DateFormatter (passing in the class's global, when called).
extension TimeInterval {
func format(timeZone: String, dateFormatter: DateFormatter) -> String {
let usableDate = Date(timeIntervalSince1970: self)
dateFormatter.timeZone = TimeZone(identifier: timeZone)
let dateString = dateFormatter.string(from: usableDate)
return dateString
}
}
If anyone's also looking at alternatives, the caching approach offered by mluton/sandmoose, here, is quite nice:
https://gist.github.com/mluton/98ab2b82bd18f7a7f762#file-cacheddateformatter-swift

Putting system date into a text field in swift

I'm new to swift and would appreciate some help with string manipulation. I'm trying to get the current date off NSDate and put it into a text field for an app I'm working on. I tried to use NSDateFormatter to put the ios system date into the international form or dd-MM-yyyy, but I just keep getting all these errors and nothing works. I could use the American date format, I just really need it to work. I don't really know swift that much, but I know that other tutorials I tried to follow on stack overflow directed me to put some code in the view controller using NSDate. I worked on some other tutorials and tried to make them do what I needed to and this is the result. It used to create a date and timestamp but I tried to cut the parts out that deal with time. I think I just made it worse.
func convertDateFormatter(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
guard let date = dateFormatter.date(from: date) else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "dd-MM-yyyy"
let timeStamp = dateFormatter.string(from: date)
return timeStamp
}
My version of swift doesn't recognize NSDate, it wants to change it to just Date, I don't know how it affects how I am supposed to go about doing this. I changed it to just Date in the code and it still doesn't work.
In addition, yesterday my mobile apps teacher and I tried to equate a custom variable and the text field, but it does not work.
var UIDateStamp = UITextField().self
I could be wording my search incorrectly but I have searched this same query all the different ways I could come up with, but every solution I have tried thus far gives me a lot of errors that my coding class and I cannot solve.
I would greatly appreciate help with this issue.
If you need to system date they you need create function without parameter.
Swift 3
func convertDateFormatter() -> String {
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy" // change format as per needs
let result = formatter.string(from: date)
return result
}
If you want a date format depending on the current locale use the timeStyle and dateStyle properties.
This code – as computed property – returns M/d/yy for the US locale
var timeStamp : String {
let formatter = DateFormatter()
formatter.timeStyle = .none
formatter.dateStyle = .short
return formatter.string(from: Date())
}
A date style medium returns MMM d, yyyy

Changing to 24-Hour Time on iPhone 6, iOS 9 leads to app crash

I developed an application in which I use a singleton for keeping a single instance of an NSDateFormatter.
My date formatter is initialized as below:
timeDateFormatter = NSDateFormatter()
timeDateFormatter.locale = NSLocale(localeIdentifier:EN_US_POSIX_LocaleIdentifier)
timeDateFormatter.dateFormat = StringDateType.DetailSigningHour.rawValue
let EN_US_POSIX_LocaleIdentifier = "en_US_POSIX"
With 24-Hour Time turned off the application runs as it should, but when going to Settings-->General-->Date&Time and turning on 24-Hour Time, then going and tapping on the app icon, the app tries to come up and then immediately exit.
I read that this may be an unknown issue for Apple.
Can you help me with some more information about this?
Update
When the system time was changed from 12-hour format to 24-hour format, my date formatter was messed up.
The good part is that the system is sending a notification (NSCurrentLocaleDidChangeNotification) letting you know that the locale has changed. All what I have done was to add an observer for this notification and to re-initialize my date formatter.
Setting the locale to en_US_POSIX, you force the 12-hour mode, regardless of the user's 24/12-hour mode setting.
I'm going to assume that you're force-unwrapping the result of timeDateFormatter.dateFromString with a wrong date format.
If you do something like this:
let timeDateFormatter = NSDateFormatter()
timeDateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX")
timeDateFormatter.dateFormat = "hh:mm"
And force-unwrap the result:
let d = timeDateFormatter.dateFromString("11:42")!
You will get a crash at runtime if the date string is more than 12h:
let d = timeDateFormatter.dateFromString("13:42")! // crash
because "hh:mm" deals with 12h format only.
To use 24h format you should use "HH:mm":
timeDateFormatter.dateFormat = "HH:mm"
And to avoid crashes, avoid force-unwrapping:
if let d = timeDateFormatter.dateFromString("11:42") {
print(d)
} else {
// oops
}
If my diagnostic is wrong, please add details to your question. :)
I do not know that issue, however I always used my formatters this way, maybe this is also convenient to you.
let formatter = NSDateFormatter()
formatter.timeStyle = NSDateFormatterStyle.ShortStyle // here are different values possible, and all are good declared.
formatter.dateStyle = .MediumStyle // Same possible values like in timeStyle.

UIDatePicker of type "Date & Time" only returns Date and not Time

I'm developing an iOS app which uses a UIDatePicker. The mode is "Date and Time" so the user can pick a date and time from the same picker. You can actually see Day,Time,Hour,Min,AM/PM in the picker.
The problem is, when I try to extract the time AND date (both important), I only get the date printed out even though it's a "Date AND Time" picker (according the Xcode and what I see during runtime).
Here is the code:
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
var date = dateFormatter.stringFromDate(sender.date)
println(date)
dateTimeLabel.text = date
dateTimeLabel.textColor = UIColor.blackColor()
It's identical to other examples I see online but I just don't understand why they get Time and Date and I only get the Date. I need the time as well!
The NSDateFormatterStyle.ShortStyle will return something like "6/20/2015, 3:45 PM" but it only returns "6/20/2015" when I print it to the console or the app.
If this is the case, is there a way I can just extract the time then since I already have the date? Honestly, from the other examples I've seen, they get both. I don't know why I only get the date.
Any help would be greatly appreciated!
You have to set timeStyle as well, e.g.
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .ShortStyle
otherwise you'll get only the "date" part.

Swift Accessing year from UIDatePicker

Just barely getting into iOS development using swift and getting a little overwhelmed sometimes trying to look at documentation and understand it. I am also currently running through Simon Allardice's iOS app development with swift essential training on Lynda.com and had a question regarding one of the objects we have instantiated in the WhatDay example.
We basically are setting up a UIDatePicker object from which we are extracting what day of the week we are looking at with the NSDateFormatter object at which point I was wondering,
which property would we need to access to get ahold of the current year that the user scrolled the wheel to?
So far we have this code to access the day of the week it was,
#IBACTION func displayDay(sender: AnyObject) {
// grab the selected data from the date picker
var chosenDate = self.datePicker.date
// create an NSDateFormatter
var formatter = NSDateFormatter()
formatter.dateFormat = "EEEE"
// grab the day and create a message
let day = formatter.stringFromDate(chosenDate)
let result = "That was a \(day)"
}
Also, he says we can use the date formatter "EEEE" to format for day of the week but I couldn't find any documentation on that online what the string codes are, any advice on where to find this information?
You can use NSCalendar for components of a date.
If you want to format you date as you did, then please look into this doc for different date formatting string
// grab the selected data from the date picker
var chosenDate = self.datePicker.date
//use NSCalenda
let myCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let myComponents = myCalendar?.components(.WeekdayCalendarUnit | .YearCalendarUnit, fromDate: chosenDate)
let weekDay = myComponents?.weekday
let year = myComponents?.year
println("year:\(year) , weekday:\(weekDay)")
var datePicker = UIDatePicker()
use it

Resources