How to use UILabel and DateFormatter to display the current time? - ios

I am trying to use the UILabel and DateFormatter to display the time (date, min, sec) whenever a user launches the APP.
I currently found this from stackoverflow
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
but it seems that I have to pass in a time into the formatter. How do I just get the UILabel to display the current time instead of a fixed time?

If you want to show the current time without passing any variables, You do so by:
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let exactlyCurrentTime: Date = Date()
print(dateFormatterPrint.stringFromDate(exactlyCurrentTime))
// e.g Set your label text:
myLabel.text = "Current Time: \(dateFormatterPrint.stringFromDate(exactlyCurrentTime))"
For example, If we want: Friday, Nov 16, 2018 | We set: EEEE, MMM d, yyyy
I do also recommend a visit of NSDateFormatter.com to understand how dateFormat works.
Best of luck

label.text = dateFormatter.string(from: Date())

Related

How to set specific time on date picker?

I am using date picker and selected datePicker mode as time. When I am loading the date picker it is showing current time.But I want to set default time always 5:00 PM.
I have tried the below way but it didn’t work for me.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.timeZone = .current
if let date = dateFormatter.date(from: "17:00") {
datePicker.date = date
}
Please help me to default to time 5:00PM always. Thank you.
A possible solution is to get the current date and set hour, minute and second accordingly
let fivePM = Calendar.current.date(bySettingHour: 17, minute: 0, second: 0, of: Date())!
datePicker.date = fivePM
Another way is to set the countDownDuration property
datePicker.countDownDuration = 61200 // 17 * 3600
Another possible answer would be:
let cal = Calendar.current
let timeZone: TimeZone = .current
var dateComp = cal.dateComponents(in: timeZone, from: Date())
(dateComp.hour, dateComp.minute, dateComp.second, dateComp.nanosecond) = (17, 0, 0, 0)
let fivePM = cal.date(from: dateComp)
datePicker.date = fivePM
Using this technique you can also get 5pm of the time of another timezone.
Notice that when debugging in Xcode, Xcode will show all dates in the console in the GMT timezone.

How to format date in 09-Nov-2014 format with DateFormatter in iOS & Swift?

I'm trying to format date in date picker. I can't seem to find the format to display date in 09-Nov-2014 format. It always displays in Nov 09, 2014 format. I did a lot of search but can't figure out which one is the correct format to input. Can anyone help me out? Tx in advance.
#objc func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.dateStyle = DateFormatter.Style.medium
dateFormatter.timeStyle = DateFormatter.Style.none
dateOfBirthTextField.text = dateFormatter.string(from: sender.date)
}
Don't set the styles. Just set the format.
You use either dateFormat or you use dateStyle and timeStyle.
Please note it's best to avoid using dateFormat for dates you wish to show to the user since your hardcoded format won't be standard for most users.
Also be aware that MM show the month number. If you want the abbreviated month name, use MMM.
You should not use dateStyle & timeStyle here you need a specific date format, your code should look like,
#objc func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateOfBirthTextField.text = dateFormatter.string(from: sender.date)
}
Hope it helps.

Get date from date picker in swift

I have created an IBOutlet to a date picker.
#IBOutlet weak var logDate: UIDatePicker!
I have also set the mode of this date picker to date.
Is there a way for me to extract the date that the user would input into the date picker?
I tried using print(logdate), however it also gives me the date along with the time. Like this 2015-10-30 07:10:03 +0000
Perhaps you want this:
let components = logDate.calendar.components([.Era, .Year, .Month, .Day],
fromDate: logDate.date)
print("\(components.era) \(components.year) \(components.month) \(components.day)")
// Output: 1 2015 10 31
Or perhaps you want this:
let formatter = NSDateFormatter()
formatter.calendar = logDate.calendar
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .NoStyle
let dateString = formatter.stringFromDate(logDate.date)
print(dateString)
// Output: Oct 31, 2015
You can try another dateStyle setting, or be more explicit by setting the dateFormat property. The dateFormat syntax can get pretty hairy. Remember to use yyyy, not YYYY, for the year part of your format. But it's MM, not mm for the month part. Example:
formatter.dateFormat = "yyyy-MM-dd"
print(formatter.stringFromDate(logDate.date))
// Output: 2015-10-31
You can extract the date inputted by the user in a date field using this code.
Note: This solution extracts the input as a string
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle // You can also use Long, Medium and No style.
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var inputDate = dateFormatter.stringFromDate(*datepicker outlet name*.date)
print(inputDate)
Used a section of code from: http://www.ioscreator.com/tutorials/display-date-date-picker-ios8-swift
Swift 5
It's more simple than it appears. Just create a var of type Date and set its value from the datePicker outlet like this.
#IBOutlet weak var yourDatePicker: NSDatePicker!
var date = Date()
#IBAction func datePickerChanged(_ sender: Any) {
date = yourDatePicker.dateValue
}
Now you can use that variable to insert date values on Core Data's attributes of type Date or something like that.
Get hour and minute in swift 5
let comp = datePickerOutlet.calendar.dateComponents([.hour, .minute], from: datePickerOutlet.date)
print(comp.hour!)
print(comp.minute!)

How can I show ONLY the date (and not the time) using NSDateFormatter?

I think the question is pretty straightforward. I need only the date to appear, and not the time. Couldn't find anything for Swift, so my code is here:
cell.date.text = NSDateFormatter.localizedStringFromDate(dates[indexPath.row],
dateStyle: .ShortStyle,
timeStyle: .ShortStyle)
Read the documentation of the method you are calling. There are four or five different possible values that you can pass for the formatting style of the date and the time. You picked a formatting style that outputs a short format. Pick instead the formatting style that does what you want. I'll give you a hint: There is one style with a "No" in the name.
Seriously, right click on "ShortStyle", and pick "Jump to Definition" from the popup menu.
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = NSLocale(localeIdentifier: #"en_US")
let d = NSDate()
let s = dateFormatter.stringFromDate(d)
Use this
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let d = NSDate()
cell.date.text = dateFormatter.stringFromDate(d)

NSDate being interpreted several hours off (minutes and day working fine)

I am updating the question to be more precise, thank you for the feedback already.
So I am setting a cell for a tableview and displaying the time of the event on the cell itself and to do so am using Parse. The date is downloading correctly from parse as evidenced by the first println, but when I make the label text equal the dateToString of the when date (which is the one from parse) it throws it off by several hours for some reason. The simulator however displays the right time on the status bar and the phones gps is set to EST as well... So I am very confused.
Here is the entire function:
func configureCell(object : PFObject)-> Void {
eventNameText.text = (object.objectForKey("name") as? String)!
var when = (object.objectForKey("when") as? NSDate)!
numEchoesText.text = String(stringInterpolationSegment: object.objectForKey("numEchoes")!)
println(when)
var formatter = NSDateFormatter()
formatter.dateFormat = "EEEE, h:mm a"
parseid = object.objectId!
if (contains(echoes, parseid)) {
echoImage.setImage(imageEchoed, forState: .Normal)
}
else {
echoImage.setImage(imageUnechoed, forState: .Normal)
}
var now = NSDate()
whenText.text = formatter.stringFromDate(when)
println(formatter.stringFromDate(now))
println(formatter.stringFromDate(when))
self.object = object
}
And here is the result:
2015-05-31 23:43:00 +0000
Tuesday, 9:30 AM
Sunday, 7:43 PM
Please note that the first time is correct but the datetostring is interpreting it as the third line. I added a middle println to display the current date in order to show that the datetostring is working correctly for the now date.
Thanks in advance for any help!!
Edit: updated answer based on new details.
Your trouble is because of the timezone. NSDate does not store any time zone information.
println(when)
--> 2015-05-31 23:43:00 +0000 // notice the timezone is 0000 / GMT
Adding a timezone to the NSDateFormatter will help you see what's going on behind the scene:
var formatter = NSDateFormatter()
formatter.dateFormat = "EEEE, h:mm a z"
println(formatter.stringFromDate(when))
--> Sunday, 7:43 PM xyz // Depends on the timezone on your device
The two represents the same point in time, but expressed in different timezones. To solve this, you need to set the timezone of the formatter to GMT:
var formatter = NSDateFormatter()
formatter.dateFormat = "EEEE, h:mm a z"
formatter.timeZone = NSTimeZone.init(name:"GMT")
println(formatter.stringFromDate(when))
--> Sunday, 11:43 PM GMT
You can remove the timezone identifier now that you get it correct. Date & time manipulation in Cocoa / iOS are a lot more complicated than other languages (Java, C#, Javascript, etc.) Sometimes I wish Apple just created a NSDate class with methods to add & subtract date/time components, switch timezone, etc. I can dream on.
Take a look at NSDateFormatter and how it works. If I do understand your question clearly, I think this should work.
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm"
dateFormatter.stringFromDate(parseDateObject)
2015-05-31 23:43:00 +0000 means "the 31st of May 2015 at 23:43:00 at +0000 from UTC".
According to your question "The simulator however displays the right time on the status bar and the phones gps is set to EST".
If you convert that date from UTC to EST you get "Sunday, 7:43 PM".
Your NSDate is therefore being interpreted perfectly.
Making reasonable assumptions about the Parse API, it looks like somebody has imported your data incorrectly.

Resources