Swift Accessing year from UIDatePicker - ios

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

Related

Getting the current date in a specific format [duplicate]

When I try to log the current date:
print(NSDate())
or
print(Date())
(in Swift 3)
Or any date object, it shows the wrong time. For example, it's about 16:12 now, but the above displayed
2016-10-08 20:11:40 +0000
Is my date in the wrong time zone? How do I fix my date to have the correct time zone?
Why is that, and how to I fix it? How do I easily display an arbitrary date in my local time zone, either in print statements or in the debugger?
(Note that this question is a "ringer" so that I can provide a simple Swift 3/Swift 2 Date/NSDate extension that lets you easily display any date object in your local time zone.
NSDate (or Date in Swift ≥ V3) does not have a time zone. It records an instant in time all over the world.
Internally, date objects record the number of seconds since the "epoch date", or Midnight on January 1, 2001 in Greenwich Mean Time, a.k.a UTC.
We normally think of dates in our local time zone.
If you log a date using
print(NSDate())
The system displays the current date, but it expresses it in UTC/Greenwich Mean Time. So the only place the time will look correct is in that time zone.
You get the same issue in the debugger if you issue the debugger command
e NSDate()
This is a pain. I personally wish iOS/Mac OS would display dates using the user's current time zone, but they don't.
EDIT #2:
An improvement on my previous use of localized string that makes it a little easier to use is to create an extension to the Date class:
extension Date {
func localString(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String {
return DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle)
}
}
That way you can just use an expression like Date().localString(), or if you want to only print the time, you can use Date().localString(dateStyle:.none)
EDIT:
I just discovered that NSDateFormatter (DateFormatter in Swift 3) has a class method localizedString. That does what my extension below does, but more simply and cleanly. Here is the declaration:
class func localizedString(from date: Date, dateStyle dstyle: DateFormatter.Style, timeStyle tstyle: DateFormatter.Style) -> String
So you'd simply use
let now = Date()
print (DateFormatter.localizedString(
from: now,
dateStyle: .short,
timeStyle: .short))
You can pretty much ignore everything below.
I have created a category of the NSDate class (Date in swift 3) that has a method localDateString that displays a date in the user's local time zone.
Here is the category in Swift 3 form: (filename Date_displayString.swift)
extension Date {
#nonobjc static var localFormatter: DateFormatter = {
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateStyle = .medium
dateStringFormatter.timeStyle = .medium
return dateStringFormatter
}()
func localDateString() -> String
{
return Date.localFormatter.string(from: self)
}
}
And in Swift 2 form:
extension NSDate {
#nonobjc static var localFormatter: NSDateFormatter = {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateStyle = .MediumStyle
dateStringFormatter.timeStyle = .MediumStyle
return dateStringFormatter
}()
public func localDateString() -> String
{
return NSDate.localFormatter.stringFromDate(self)
}
}
(If you prefer a different date format it's pretty easy to modify the format used by the date formatters. It's also straightforward to display the date and time in any timezone you need.)
I would suggest putting the appropriate Swift 2/Swift 3 version of this file in all of your projects.
You can then use
Swift 2:
print(NSDate().localDateString())
Swift 3:
print(Date().localDateString())
A simple way to correct the Date for your timezone would be to use TimeZone.current.secondsFromGMT()
Something like this for a local timestamp value for example:
let currentLocalTimestamp = (Int(Date().timeIntervalSince1970) + TimeZone.current.secondsFromGMT())

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

How to get the specific date in iOS?

I'm working on a project where I have labels and images that change on a daily basis. My idea on how to go about this is I add assets for the images and have multiple files where I take the text (that contains the quote).
Two questions:
Is there a better way of approaching this? (I'm fairly new to iOS, so I'm wondering if this is sound).
How can I take the current day as in: May 22? (I just want to know how to get "22").
you need to use NSDate
// Option 1
let date = NSDate() // today
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "dd"
let d = dateStringFormatter.stringFromDate(date)
// d = "22"
// Option 2
let d = NSCalendar.currentCalendar().component(.Day, fromDate: NSDate()) // thanks Leo-Dabus
Reference: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/
Try taking a look at this stackoverflow link on getting the current date.
How to get the current time as datetime
According to noliv in the article you should be able do :
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
Hope this helps

SWIFT: How do I add hours to NSDate object

I generate a NSDate object from string.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let stringToDate = dateFormatter.dateFromString(dateFromService) // 2015-07-20 12:00:43 +0000
I get this string value from webserver. I need to modify for personal device timezone. Want to add hours this stringToDate object but not work
var addHours : Int = 2 // 2 hours will be added
var newDate = stringToDate.dateByAddingTimeInterval(addHours)
Use NSCalendarComponents:
let calendar = NSCalendar.currentCalendar()
let newDate = calendar.dateByAddingUnit(
.CalendarUnitHour, // adding hours
value: 2, // adding two hours
toDate: oldDate,
options: .allZeros
)
Using NSCalendar will account for things like leap seconds, leap hours, etc.
But as Duncan C's answer points out, simply adding hours is definitely the wrong approach. Two time zones won't always be separated by the same amount of time. Again, this is something especially true when we take daylight savings into account. (For example, the United States doesn't start/end daylight savings on the same days as Europe, and Arizona doesn't even do daylight savings).
You're asking the wrong question. This is what's known as an "XY Problem".
You should be asking "How do I display a date string I get from a web server in the user's local time zone."
NSDate represents a date/time in an abstract form that does not contain a time zone. You convert it to a specific time zone for display. Do not try to add/subtract hours to an NSDate to offset for time zones. That is the wrong approach.
The correct answer is simple. Create a second date formatter and don't set it's timezone to GMT. It defaults to the user's local time zone.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let date = dateFormatter.dateFromString(dateFromService)
let outputDatedateFormatter = NSDateFormatter()
outputDatedateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//leave the time zone at the default (user's time zone)
let displayString = outputDateFormatter.stringFromDate(date)
println("Date in local time zone = \(displayString)")
For Swift 3 you can use this function:
//get next date by adding hours func
getNewDateAfterAddingHours(hoursToAdd:NSInteger, oldDate:Date) -> Int64 {
let calendar = Calendar.current
let newDate = calendar.date(byAdding: .hour, value: hoursToAdd, to: oldDate)
return Int64((newDate?.timeIntervalSince1970)!)
}
If you are doing it more often, check out library called SwiftMoment (inspired by the same .js library), which allows you to do following (and much more!):
// Create date using moment library
let myDate = moment(myString)
// Add one hour
let dateWithAddedHour = myDate + 1.hours
Moment is a wrapper around NSDate instance, while Duration (which is what you get from Int.hours, Int.minutes etc.) wraps an NSTimeInterval value.
Implementing this should take you just a moment! (Pun intended).

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

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))

Resources