I'm using a textfield that uses a datePicker instead of a keyboard. It displays the format as a string that looks like this 'May 31, 2015 at 12:30'(taken from the println(delivery.text) function.) I want to change the date to NSDate, so I can compare to current date. Any suggestions?
#IBOutlet weak var pickUp: UITextField!
#IBOutlet weak var delivery: UITextField!
let dateFormat: NSDateFormatter = NSDateFormatter()
let datePicker: UIDatePicker = UIDatePicker()
let dateFormat2: NSDateFormatter = NSDateFormatter()
let datePicker2: UIDatePicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
dateFormat.dateStyle = NSDateFormatterStyle.LongStyle
dateFormat.timeStyle = NSDateFormatterStyle.LongStyle
datePicker.datePickerMode = UIDatePickerMode.DateAndTime
datePicker.addTarget(self, action: Selector("updateDateField:"), forControlEvents:UIControlEvents.ValueChanged)
pickUp.inputView = datePicker
dateFormat2.dateStyle = NSDateFormatterStyle.LongStyle
dateFormat2.timeStyle = NSDateFormatterStyle.LongStyle
datePicker2.datePickerMode = UIDatePickerMode.DateAndTime
datePicker2.addTarget(self, action: Selector("updateDateField:"), forControlEvents:UIControlEvents.ValueChanged)
delivery.inputView = datePicker2
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.toolbarHidden = false
self.tabBarController?.tabBar.hidden = true
}
func updateDateField(sender: UIDatePicker) {
if sender == datePicker
{
pickUp.text = dateFormat.stringFromDate(sender.date)
}
if sender == datePicker2
{
delivery.text = dateFormat2.stringFromDate(sender.date)
}
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy 'at' h:mm:ss a"
if let date = dateFormatter.dateFromString("May 31, 2015 at 12:30:15 PM") {
println(date)
}
if you need some reference for date formatting you can use this one:
You can try using the DateFormatter to format your string into a date and then pulling the NSDate object out like so. In your case, something like this would probably suit your needs.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM d, yyyy at H:mm"
let date = dateFormatter.dateFromString(//insert string here)
Refer to the original documentation if you have further questions or this handy guide for formatting guidelines.
Related
If you look at the iPhone alarm app I can see that if I don't set the time in the date picker, the alarm is set to the current time.
#IBAction func selectAlarm(_ sender: Any) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
let date = dateFormatter.string(from: datePicker.date)
print("date : \(date)")
}
The above code outputs the time set when the datePicker is moved. How to output current time as default without moving datePicker as above?
Try this
#IBAction func selectAlarm(_ sender: Any) {
let newDatePicker = UIDatePicker()
newDatePicker.date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let currentTime = dateFormatter.string(from: newDatePicker.date)
print("time : \(currentTime)")
self.yourTextField.text = currentTime
}
Put the datePicker.date outside the func selectAlarm(), eg: in viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
datePicker.datePickerMode = .time
datePicker.date = Date()
}
The date Picker works and gives date even without moving datePicker. I have tested it.
#IBAction func getCurrentTime() {
var formatter = DateFormatter()
formatter.dateFormat = "DD/MM/YY"
var dd = formatter.string(from: datePicker.date)
print(dd)
}
Problem is with your code.
My code below creates a date picker and has it select a date and time. All I want to do is when the date picker's date and time match the user's phone's date and time is to print the line "cool". That's it. I commented the line that is causing me problems.
import UIKit
var dateFormatter : DateFormatter!
let datePicker2 = UIDatePicker();
let date = Date()
class ViewController: UIViewController {
#IBOutlet var dateLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let datePicker : UIDatePicker = UIDatePicker(frame: CGRect(x: 0,y: 330,width: self.view.frame.size.width,height: 220))
datePicker.datePickerMode = UIDatePickerMode.dateAndTime
self.view.addSubview(datePicker)
datePicker.addTarget(self, action: #selector(ViewController.change(_:)), for: UIControlEvents.valueChanged)
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd hh:mm"
}
#IBAction func change(_ sender : UIDatePicker)
{
dateLabel.text = dateFormatter.string(from: sender.date)
///print cool line; what I have does not work
if dateLabel.text == String(describing: date){
print("cool")
}
}
}
Your primary issue is how you compare the two dates. You should be using the same date formatter to convert both Date instances to strings in the same format. Then you can compare the two strings.
#IBAction func change(_ sender : UIDatePicker)
{
let pickerString = dateFormatter.string(from: sender.date)
let nowString = dateFormatter.string(from: Date())
dateLabel.text = pickerString
if pickerString == nowString {
print("cool")
}
}
You are also using the wrong format. You need "yyyy-MM-dd HH:mm". YYYY is slightly different. You always want yyyy unless you have a clearly understood and specific need to use YYYY. And for the hour you want HH instead of hh. HH is a 24-hour hour while hh is a 12-hour hour. Only use hh is you also use a (for AM/PM).
And your properties should be inside the class, not outside.
Move datePicker2 inside the class.
date is now obsolete based on my answer so you can remove it completely.
dateFormatter should also be moved inside the class.
What I am trying to accomplish:
I am trying to make an enter button that checks the date in the UITextField to see if it is before the current date(any date that is today) and if the date in the UITextField is in the past, I want to throw an error/alert to tell the user to enter a date in the future--possibly a week or month from the current date.
A little background:
I made a viewController with a textfield that a user is going to enter a
date into and the way this works is the user presses on the textField and
a datePicker pops up allowing them to update the textField with the datePicker.
The problem I am running into:
This all works fine until I want to compare the date in the textField with the current date. This is because the date in the textField is a string and not a date that NSDate can recognize.
My question basically is
How do I convert the string date in the TextField into a format that NSDate can recognize?
Here is my code for my enterButton function:
#IBAction func enterButton(sender: AnyObject) {
let dateFormatter = NSDateFormatter()
var raceDate = raceDateTextField.text
let currentDate = NSDate()
raceDate = dateFormatter.stringFromDate(sender.date)
if currentDate.compare(raceDate) == NSComparisonResult.OrderedDescending {
print("Race Date is earlier than Current Date")
}
}
I'm getting the error
cannot convert value of type 'String?' to expected argument type 'NSDate' # the line below
if currentDate.compare(raceDate) == NSComparisonResult.OrderedDescending {
print("Race Date is earlier than Current Date")
}
Here is the my code for updating my textField using a datePicker just for reference:
#IBAction func textFieldEditing(sender: UITextField) {
let datePicker:UIDatePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePicker
datePicker.addTarget(self, action: #selector(SecondViewController.datePickerValueChanged), forControlEvents: UIControlEvents.ValueChanged)
}
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
raceDateTextField.text = dateFormatter.stringFromDate(sender.date)
}
Am I going about this wrong logically?
Any help with this will be greatly appreciated! :)
EDIT/UPDATE!
I made the changes like you guys advised and I am getting the same error at the same line.
Here is my updated code:
#IBAction func enterButton(sender: AnyObject) {
let dateFormatter = NSDateFormatter()
var raceDate = raceDateTextField.text
dateFormatter.dateFormat = "dd/MM/yyyy"
var minimumDate: NSDate? = NSDate()
raceDate = dateFormatter.stringFromDate(sender.date)
if minimumDate!.compare(raceDate) == NSComparisonResult.OrderedDescending {
print("Race Date is earlier than Current Date")
}
}
I think the (sender.date) parameter is wrong # line:
raceDate = dateFormatter.stringFromDate(sender.date)
Right now I'm thinking I entered in the wrong parameter(sender.date) because raceDate still shows up as a string data type in the if statement.
Swift 3:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM, dd, yyyy"
let raceDate = raceDateTextField.text
let date = dateFormatter.date(from: raceDate!)
let minimumDate = NSDate()
if minimumDate.compare(date!) == ComparisonResult.orderedDescending {
}
The text that is currently in your textField is a String. You need to run that through a dateFormatter and get the date (NSDate). Afterwards you can compare it to the current date.
It's basically the same thing as when you set the text in your textField, but the other way around.
see: https://developer.apple.com/reference/foundation/nsiso8601dateformatter/1643127-datefromstring
You said that you want to compare the date in the textField with the current date.
So just create and set a minimum date for the date picker to today. var minimumDate: NSDate?
For example:
if minimumDate.compare(raceDate) == NSComparisonResult.OrderedDescending {
print("Race Date is earlier than Current Date. Are you a time traveler?")
}
#IBAction func enterButton(sender: AnyObject) {
let myDate = raceDateTextField.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.dateFromString(myDate)!
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.stringFromDate(date)
}
Got it working correctly, thanks to #Amit Jagesha, #tymac, #Andrei Filip, and #Leo Dabus
Here is the end product in case anybody else has a similar problem and for future reference.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM, dd, yyyy"
let raceDate = raceDateTextField.text
let date = dateFormatter.dateFromString(raceDate!)
let minimumDate = NSDate()
if minimumDate.compare(date!) == NSComparisonResult.OrderedDescending {
}
This is my first ever attempt at Swift or an iPhone app, so needless to say I'm not sure how to do many things at this point.
I want to show the date like this in my textfield
02 Feb 2016
But right now it displays like this
2/7/16
here is my code
#IBAction func dateTextFieldBeginEditing(sender: UITextField) {
// let datePickerView:UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
}
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
departureDateTextField.text = dateFormatter.stringFromDate(sender.date)
}
Set date format like this!! This will give you date like 02 Feb 2016.
Also remove dateStyle and timeStyle property from your code.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
dateFormatter.stringFromDate(NSDate())
This gives me output as 09 FEB 2016
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
let dateString = dateFormatter.stringFromDate(sender.date)
departureDateTextField.text = dateString
}
1) Add an Extension of NSDate
extension NSDate {
func dateStringWithFormat(format: String) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.stringFromDate(self)
}
}
2) Make two public variables
var datePicker:UIDatePicker?
let formatter = NSDateFormatter()
3) Add to UIDatePicker
let dateString = NSDate().dateStringWithFormat("yyyy-MM-dd")
print("Today's Date: "+dateString)
datePicker?.date = formatter.dateFromString(dateString)!
func datePicker(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
//// dd MMM yyyy == 02 Feb 2016
let dateData = dateFormatter.stringFromDate(sender.date)
departureDateTextField.text = dateData
}
let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .NoStyle)
print(timestamp)
override func viewDidLoad()
{
super.viewDidLoad()
self.datePicker.backgroundColor = .white
self.datePicker.datePickerMode = .date
let loc = Locale.init(identifier: "pt-BR")
var calendar = Calendar.current
calendar.locale = loc
self.datePicker.calendar = calendar
self.datePicker.locale = loc
self.datePicker.addTarget(self, action: #selector(ViewController.handleDatePicker), for: UIControl.Event.valueChanged)
}
#objc func handleDatePicker()
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
let loc = Locale.init(identifier: "pt-BR")
dateFormatter.locale = loc
print(dateFormatter.string(from: self.datePicker.date))
}
I am teaching myself swift and I am still very new but I decided to make a simple app that prints the current time when you press a button. the code from the viewcontroller file is as follows:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet weak var LblTime: UILabel!
#IBAction func BtnCalltime(sender: AnyObject) {
var time = NSDate()
var formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM"
var formatteddate = formatter.stringFromDate(time)
LblTime.text = time
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I am having an issue with the line:
LblTime.text = time
I keep getting the error:
Cannot assign a value of type 'NSDate' to a value of type 'String?'
I have tried using:
lblTime.text = time as! string?
And:
lblTime.text = time as! string
but it does still not work, I would be very appreciative of some help.
Thanks
You need use a value from formatter.
#IBAction func BtnCalltime(sender: AnyObject) {
var time = NSDate()
var formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM"
var formatteddate = formatter.stringFromDate(time)
LblTime.text = formatteddate
}
You made the string from an NSDate already, you just aren't using it.
lblTime.text = formatteddate
Date is now preferred over NSDate. It is an overlay class meaning both will work, but Date but has a lot of advantages, this answer lists some of those.
Here is how to format a date to a string using Date instead of NSDate.
var time = Date()
var formatter = DateFormatter()
formatter.dateFormat = "MMM d yyyy, h:mm:ss a"
let formattedDateInString = formatter.string(from: time)
dateLabel.text = formattedDateInString
A great site to get the formatter strings is http://nsdateformatter.com/
I had no idea that "MMM d yyyy, h:mm:ss a" would equal Mar 1, 7:02:35 AM but the site makes it easy.