How to display current time on text label? - swift

I have just started with Swift and I am developing one simple application where I want to display a current time on display with text label.
Can any one please help me about that?

Use a date formatter to format the date.
var dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .MediumStyle
var timeString = "The time is: \(dateFormatter.stringFromDate(NSDate()))"
Set timeString to your label's text property. Run it on an NSTimer to keep it up to date.

Display Live Time/Date in labels.
#IBOutlet weak var dateLabel: UILabel!
#IBOutlet weak var timeLabel: UILabel!
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
dateLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .long, timeStyle: .none)
timeLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
}
#objc func tick() {
dateLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .long, timeStyle: .none)
timeLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
}

Swift 4:
var currentDateTime = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .medium
yourLabel.text = "\(dateFormatter.string(from: currentDateTime))"

Swift 3.0
Method 1 (Using date formatter)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .medium
let timeString = "The time is: \(dateFormatter.string(from: Date() as Date))"
label.text = String(timeString)
Method 2 (Get hour,minute,second seperately)
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
label1.text = String(hour) + ":" + String(minute) + ":" + String(seconds)
label2.text = String(day) + ":" + String(month) + ":" + String(year)

Related

set Date to DatePicker and listener for value changing and removing AR prefix

I'm using DatePicker with my country timeZone year month day are okay but there is AP prefix on picker which I don't need how can I get ride of it ?
I have searched a lot but there is nothing about it
update :
override func viewDidAppear(_ animated: Bool) {
datepicker2.datePickerMode = .date
datepicker2.timeZone = TimeZone(identifier: "IRST")
datepicker2.calendar = Calendar(identifier: .persian)
datepicker2.locale = Locale(identifier: "fa_IR")
datepicker2.date=self.minDate
datepicker2.addTarget(self, action: Selector("datepickerAction"), for: .valueChanged)
}
I need my native date and my time zone and this is datePicker initializing
func datepickerAction(){
let date = self.datepicker2.date
let components = Calendar.current.dateComponents([.month, .day,.year], from: date)
let hour = components.month
let minute = components.day
let yr=components.year
print(hour,minute,yr)
}
this is the listener which is not working properly not change the date. each time print the same date.
screenshot
http://uploadkon.ir/2Ui
I think you have to pass the parameter in the function like this...
override func viewDidAppear(_ animated: Bool) {
datepicker2.datePickerMode = .date
datepicker2.timeZone = TimeZone(identifier: "IRST")
datepicker2.calendar = Calendar(identifier: .persian)
datepicker2.locale = Locale(identifier: "fa_IR")
datepicker2.addTarget(self, action: #selector(datepickerAction(_:)), for: .valueChanged)
}
So, now you can get the date every time that change in the picker...
func datepickerAction(_ sender: UIDatePicker){
let date = self.datepicker2.date
let components = Calendar.current.dateComponents([.month, .day,.year], from: date)
let hour = components.month
let minute = components.day
let yr=components.year
print(hour,minute,yr)
}

string to date in my timeZone make wrong date

I'm trying to convert String to date in my country time zone but the result is not as formatted I did
let dbl = TimeInterval(longDate)
let date = Date(timeIntervalSince1970: dbl / 1000)
let formatter = DateFormatter()
print(longDate)
formatter.calendar = Calendar(identifier: .persian)
formatter.locale = Locale(identifier: "fa_IR")
formatter.timeZone = TimeZone(identifier: "IRST")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let a = formatter.string(from: date)
resultDate = dateFormatter.date(from: a)
print(reslutDate,a) //2018-08-02 11:56:28 +0000 incorrect time 1397-05-11 15:56:28 correct time
in print line date is correct but the time is incorrect. I need this time to my Timepicker
update :
I have listener for time when I change the time set the value on textField
like below :
self.timePickerFrom.addTarget(self, action: #selector(self.dateChangedFrom(_:)), for: .valueChanged). // the listener
and this is what I do for changing value :
let date = self.timePickerFrom.date
print(date)
let components = Calendar.current.dateComponents([.hour, .minute], from: date)
let hour = components.hour!
let minute = components.minute!
self.timeOfloadingLable.text = "\(hour):\(minute)"
but the problem is when I change minute goes 30Min forward
Your are doing it in wrong way, You should set format on date picker not the date of date picker.
Look at this code:
#IBOutlet weak var epoch: UITextField!
#IBOutlet weak var dateTimePicker: UIDatePicker!
#IBAction func presentDate(_ sender: UIButton) {
guard let text = epoch.text else {return}
guard let epoch = Double(text) else {return}
guard let date = convertDate(epoch: epoch) else {return}
dateTimePicker.date = date
dateTimePicker.timeZone = TimeZone(identifier: "IRST")
dateTimePicker.locale = Locale(identifier: "fa_IR")
dateTimePicker.calendar = Calendar(identifier: Calendar.Identifier.persian)
}
private func convertDate(epoch: Double) -> Date? {
let date = Date(timeIntervalSince1970: epoch)
return date
}
Is it what you mean?
I just uploaded a sample project, you can check it here: sample project

Do not count seconds

I have a UIDatePicker with the mode time. The date picker lets you pick an hour and minute. I need it to remember the hour and minute not the seconds.
When the app is running the date picker will take the hours and minute the user selected and add the seconds from the time you took to the remembered time.
An example when I select 2:00 pm from the UIDatePIcker this is what I get:
2017-03-07 02:00:36 +0000
However i want to either set the seconds to 00 or remove them like this:
2017-03-07 02:00 +0000
2017-03-07 02:00:00 +0000
Here is my code:
#IBOutlet var datePicker: UIDatePicker!
#IBAction func datePickerchanged(_ sender: Any) {
setDateAndTime()
Check()
let clockString: String = formatADate()
if str == clockString{
takePhoto = true
}
}
func setDateAndTime() {
timercount = Timer.scheduledTimer(timeInterval: 0, target: self, selector: #selector(Check), userInfo: nil, repeats: true)
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm"
_ = formatter.string(from: datePicker.date)
str = dateFormatter.string(from: (datePicker?.date)!)
RunLoop.main.add(timercount, forMode: RunLoopMode.commonModes)
print("setdate ran")
Check()
}
func formatADate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.dateFormat = "hh:mm"
let date = NSDate()
let output = dateFormatter.string(from: date as Date)
print(output)
return output
}
func Check(){
let nowdate = NSDate()
let date2 = datePicker?.date
let elapsed = date2?.timeIntervalSince(nowdate as Date)
print(str)
print(Date())
print(datePicker.date)
if Int(elapsed!) == 0{
takePhoto = true
}
Please help
To modify Date, I prefer to use https://github.com/MatthewYork/DateTools.
let dateWithZeroSeconds = Date(year:datePicker.date.year, month:datePicker.date.month, day:datePicker.date.day, hour:datePicker.date.hour, minute:datePicker.date.minute, second:0)
You could also do a similar transform with DateComponents, but DateTools is a very nice wrapper around all of that.

UIPickerView selected time to run code

I have added in a UIPickerView and currently have it store the selected time as a string. I want the app to carry out a simple line of code when the time that was selected on the pickerview is the time in the real world. Here is the code that I have added.
For the Clock, used to find the real world time:
let clockString: String = formatADate()
func formatADate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.dateFormat = "hh:mm:ss a"
let date = NSDate()
let output = dateFormatter.string(from: date as Date)
print(output)
return output
}
Here is the code for the UIPickerView:
#IBOutlet var dateTimeDisplay: UILabel!
#IBOutlet var datePicker: UIDatePicker!
#IBAction func datePickerchanged(_ sender: Any) {
setDateAndTime()
}
func setDateAndTime() {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm:ss a"
_ = formatter.string(from: datePicker.date)
str = dateFormatter.string(from: (datePicker?.date)!)
dateTimeDisplay.text = str
}
And here is what I want to happen when the selected time and the real world time match up:
takePhoto = true
When the pick date the start one timer function
call the function in picker
var timercount = Timer()
viewdidload()
{
timercount = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Check), userInfo: nil, repeats: true)
}
Func Check()
{
let nowdate = NSDate()//two date declare global Var
let date2 = datePicker?.date //chek the Time How Much Time Remain
let elapsed = date2?.timeIntervalSince(nowdate as Date)
if Int(elapsed!) == 0
{
takePhoto = true
}
}

Swift: Cannot convert value of type 'NSDate' to expected argument type 'NSDateComponents'

Anyone know how i can solve this? I get this error:
¨cannot convert value of type 'NSDate' to expected argument type 'NSDateComponents'¨ on line:
The error occurred at the line:
let competitionDay = userCalendar.dateFromComponents(competitionDate)!
This is a more complete excerpt of the code:
func Date() {
// 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:NSDate = myDatePicker.date
competitionDate.timeIntervalSinceNow
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)
//here we change the seconds to hours,minutes and days
let competitionDayDifference = calendar.components([.Day, .Hour, .Minute],
fromDate: currentDate!, toDate: competitionDay, options: NSCalendarOptions())
//finally, here we set the variable to our remaining time
let daysLeft = competitionDayDifference.day
let hoursLeft = competitionDayDifference.hour
let minutesLeft = competitionDayDifference.minute
In your original question you were calling dateFromComponents, which converts a NSDateComponents to a NSDate, but supplied it a competitionDate, which is already a NSDate. And the compiler was simply informing you of this error.
--
As an aside, you populate a NSDateComponents with the .Hour, .Minute, .Second, and .Nanosecond from a NSDate, but then proceed to try to save references to the components.year and components.month and components.day even though you didn't specify that those components should be included in the NSDateComponents.
--
Below you say:
It's a Countdown app and i had it running until i wanted a DatePicker to choose the date i am counting down. The competitionDate is the due date
If that's indeed what you want, then perhaps NSDateComponents isn't needed at all. I'd probably just use NSDateComponentsFormatter method stringFromDate:toDate: to show the user a nice string representation of the amount of time between two NSDate objects.
For example:
class ViewController: UIViewController {
#IBOutlet weak var datePicker: UIDatePicker!
#IBOutlet weak var label: UILabel!
weak var timer: NSTimer?
let formatter: NSDateComponentsFormatter = {
let _formatter = NSDateComponentsFormatter()
_formatter.allowedUnits = [.Year, .Month, .Day, .Hour, .Minute, .Second]
_formatter.unitsStyle = .Full
return _formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
datePicker.date = NSDate().dateByAddingTimeInterval(1000) // initialize it to whatever you want
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "didFireTimer:", userInfo: nil, repeats: true)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
timer?.invalidate()
}
func didFireTimer(timer: NSTimer) {
label.text = formatter.stringFromDate(NSDate(), toDate: datePicker.date)
}
}