create if statement based on time - swift

I want my swift code to follow a if statement based on a certain time. My timer is in military time right now. So I want to do something like if the hour in time is 01:00 to 01:59. Then the view background color should turn blue. So I am just trying to control the hour time in the time style.
import UIKit
class ViewController: UIViewController {
var box = UILabel()
#objc func tick() {
box.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
}
var timer = Timer()
var currentDateTime = Date()
lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm" // or "hh:mm a" if you need to have am or pm symbols
return formatter
}()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
dateFormatter.timeStyle = .medium
box.text = "\(dateFormatter.string(from: currentDateTime))"
}
override func viewDidLoad() {
super.viewDidLoad()
box.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)
box.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(box)
box.backgroundColor = .red
NSLayoutConstraint.activate([
box.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5),
box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
box.centerXAnchor.constraint(equalTo: view.centerXAnchor),
box.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}

If I understand exactly what you want to do, this code should help you:
...
var box = UILabel()
#objc func tick() {
box.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
let minutesNow = getMinutesFromDate(date: Date())
if minutesNow >= 60 && minutesNow < 120 {
box.backgroundColor = .blue
}
else {
box.backgroundColor = .red
}
}
func getMinutesFromDate(date: Date) -> Int {
let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: date)
let minutes = ((dateComponents.hour ?? 0) * 60) + (dateComponents.minute ?? 0)
return minutes
}
...

Related

How to send Date and Time separately to backend in swift?

fromDateLabel.text getting date and time from datepicker.. which i need to send date and time seperatedly to backend
when i do DateFormatter date is coming correctly but in time, only two digit values are working means time taking 10, 11, 12 O'Clocks. if i take 1,2,3,4,5 its not working
code: here single digit time not working
var fromDateArr = fromDateLabel.text!.components(separatedBy: ",")
fromDate = fromDateArr[0]
fromTime = fromDateArr[1].replacingOccurrences(of: " ", with: "")
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy"
let showDateFrom = inputFormatter.date(from: fromDate)
inputFormatter.dateFormat = "dd-MM-yyyy"
formateFromdate = inputFormatter.string(from: showDateFrom!)
print("formate from date \(formateFromdate)")
if i formate date and time like below nothing works
let fromDate = fromDateLabel.text!
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy, hh:mm:ssa"
guard let showDateFrom = inputFormatter.date(from: fromDate) else { return }
inputFormatter.dateFormat = "MM/dd/yyyy" // -> to get date only
formateFromdate = inputFormatter.string(from: showDateFrom)
print("from date: ", formateFromdate)
inputFormatter.dateFormat = "hh:mm a" // -> to get time only
formateFromTime = inputFormatter.string(from: showDateFrom)
print("from time")
How to send date and time separately to backend.. with 1 to 12hrs time
NOTE: if its 8 o clock then the out put time should be 08:15, not 8:15.. thats the issue.. please help me with code
Design
import UIKit
class ViewController: UIViewController{
#IBOutlet weak var txtdate: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.txtdate.setInputViewDatePicker(target: self, selector: #selector(tapDone)) //1
}
#objc func tapDone() {
if let datePicker = self.txtdate.inputView as? UIDatePicker {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "MM/dd/yy, hh:mm a"
self.txtdate.text = dateformatter.string(from: datePicker.date)
}
self.txtdate.resignFirstResponder()
}
#IBAction func showClk(_ sender: Any) {
let fromDate = txtdate.text!
print(fromDate)
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy, hh:mm a"
guard let showDateFrom = inputFormatter.date(from: fromDate) else { return }
inputFormatter.dateFormat = "MM/dd/yyyy" // -> to get date only
let formateFromdate = inputFormatter.string(from: showDateFrom)
print("from date: ", formateFromdate)
inputFormatter.dateFormat = "hh:mm a" // -> to get time only
let formateFromTime = inputFormatter.string(from: showDateFrom)
print("from time" ,formateFromTime)
}
}
extension UITextField {
func setInputViewDatePicker(target: Any, selector: Selector) {
// Create a UIDatePicker object and assign to inputView
let screenWidth = UIScreen.main.bounds.width
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))//1
datePicker.datePickerMode = .date
self.inputView = datePicker
// Create a toolbar and assign it to inputAccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 44.0))
let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancel = UIBarButtonItem(title: "Cancel", style: .plain, target: nil, action: #selector(tapCancel))
let barButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
toolBar.setItems([cancel, flexible, barButton], animated: false)
self.inputAccessoryView = toolBar
}
#objc func tapCancel() {
self.resignFirstResponder()
}
}

FSCalendar check today date

How can I check that I clicked on today date?
https://github.com/WenchaoIOS/FSCalendar
I got the below output:
todaydateString = 2020-05-18
dateString = 2020-05-17
which is not matching:
import UIKit
class LoadViewExampleViewController: UIViewController, FSCalendarDataSource, FSCalendarDelegate {
private weak var calendar: FSCalendar!
fileprivate lazy var dateFormatter1: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
let dateString = "2020-05-15"
let dateString1 = "2020-05-16"
let dateString2 = "2020-05-13"
var selectedDates = NSMutableArray()
override func loadView() {
selectedDates = [dateString, dateString1, dateString2]
let view = UIView(frame: UIScreen.main.bounds)
view.backgroundColor = UIColor.groupTableViewBackground
self.view = view
let height: CGFloat = UIDevice.current.model.hasPrefix("iPad") ? 400 : 300
let calendar = FSCalendar(frame: CGRect(x: 0, y: self.navigationController!.navigationBar.frame.maxY, width: self.view.bounds.width, height: height))
calendar.dataSource = self
calendar.delegate = self
calendar.backgroundColor = UIColor.clear
calendar.appearance.todayColor = UIColor.gray
// calendar.appearance.borderDefaultColor = UIColor.black
//calendar.appearance.borderRadius = 0
self.view.addSubview(calendar)
self.calendar = calendar
}
func calendar(_ calendar: FSCalendar, didDeselect date: Date, at monthPosition: FSCalendarMonthPosition) {
let todaydate = Date()
let dateString = self.dateFormatter1.string(from: date)
let todaydateString = self.dateFormatter1.string(from: todaydate)
print("todaydateString = \(todaydateString)")
print("dateString = \(dateString)")
if dateString == todaydateString
{
print("GOOD")
}
}
func calendar(_ calendar: FSCalendar, imageFor date: Date) -> UIImage? {
let dateString = self.dateFormatter1.string(from: date)
if self.selectedDates.contains(dateString) {
let image : UIImage = UIImage(named: "checkbox_Tick")!
return image
}
return UIImage()
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "FSCalendar"
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
if monthPosition == .previous || monthPosition == .next {
calendar.setCurrentPage(date, animated: true)
}
}
}

I Can't Change label.text with Timer in Swift 3

#IBOutlet var timeLabel: UILabel!
var timer = Timer()
let now = Date()
let userCalendar = Calendar.current
let formatter = DateFormatter()
func printTime() {
formatter.dateFormat = "MM/dd/yy hh/mm/ss a"
let startTime = now
let endTime = formatter.date(from: "01/01/17 00/00/00 a")
let difference = userCalendar.dateComponents([.month, .day, .year, .hour, .minute, .second], from: startTime, to: endTime!)
timeLabel.text = "Yılbaşına \(difference.month!) ay, \(difference.day!) gün, \(difference.hour!) saat, \(difference.minute!) dakika, \(difference.second!) saniye kaldı"
print("hello world")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: #selector(ViewController.printTime),
userInfo: nil,
repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
When it is running
I am using Xcode 8 with Swift 3. When I run this code it is writes to console "hello world" every second but it is not update label when timer is running. I want to countdown for label for every second.
Try this:
DispatchQueue.main.after(when: .now() + 1.0) { //after one second
timeLabel.text = "Yılbaşına \(difference.month!) ay, \(difference.day!) gün, \(difference.hour!) saat, \(difference.minute!) dakika, \(difference.second!) saniye kaldı"
}
I solved. First I delete "let now = Date()" line and I changed "let startTime = Date()

Swift countdown timer- displays days hours seconds remaining

Hello I am very new to swift and I was trying to create an app that counts down to an event on a specific date. I want it to show the number of days hours and seconds left until the specified date but I cannot figure out how to do this.
Please help!
Swift 4
var releaseDate: NSDate?
var countdownTimer = Timer()
func startTimer() {
let releaseDateString = "2018-09-16 08:00:00"
let releaseDateFormatter = DateFormatter()
releaseDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
releaseDate = releaseDateFormatter.date(from: releaseDateString)! as NSDate
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
#objc func updateTime() {
let currentDate = Date()
let calendar = Calendar.current
let diffDateComponents = calendar.dateComponents([.day, .hour, .minute, .second], from: currentDate, to: releaseDate! as Date)
let countdown = "Days \(diffDateComponents.day ?? 0), Hours \(diffDateComponents.hour ?? 0), Minutes \(diffDateComponents.minute ?? 0), Seconds \(diffDateComponents.second ?? 0)"
print(countdown)
}
This works like a charm:
var releaseDate: NSDate?
override func viewDidLoad() {
super.viewDidLoad()
let releaseDateString = "2016-03-02 22:00:00"
let releaseDateFormatter = NSDateFormatter()
releaseDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
releaseDate = releaseDateFormatter.dateFromString(releaseDateString)!
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countDownDate", userInfo: nil, repeats: true)
}
func countDownDate() {
let currentDate = NSDate()
let diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second], fromDate: currentDate, toDate: releaseDate!, options: .MatchFirst)
let countdown = "Months: \(diffDateComponents.month), Days: \(diffDateComponents.day), Hours: \(diffDateComponents.hour), Minutes: \(diffDateComponents.minute), Seconds: \(diffDateComponents.second)"
print(countdown)
}
Swift 3
var releaseDate: Date?
override func viewDidLoad() {
super.viewDidLoad()
let releaseDateFormatter = DateFormatter()
releaseDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
releaseDate = releaseDateFormatter.date(from:releaseDateString!)!
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.countDownDate), userInfo: nil, repeats: true)
}
func countDownDate() {
let date = Date()
let calendar = Calendar.current
let diffDateComponents = calendar.dateComponents([.day, .hour, .minute, .second], from: date, to: releaseDate!)
let countdown = "Days \(diffDateComponents.day), Hours: \(diffDateComponents.hour), Minutes: \(diffDateComponents.minute), Seconds: \(diffDateComponents.second)"
print(countdown)
}
This is what I had to do for my app.
import UIKit
import Foundation
var timer = Timer()
var currentTime = Date()
var compareTime = Date().addingTimeInterval(-21600)
func setupButtonTitle()
{
if UserDefaults.standard.object(forKey: "count6") == nil
{
button.setTitle("PRESS", for: .normal)
button.backgroundColor = .green
}
else
{
button.setTitle("PRESS" + "\nIN " + "\(startTimer()))" , for: .normal)
}
button.addTarget(self, action: #selector(buttonTap), for: .touchUpInside)
}
func startTimer()
{
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(sixHourCountdown), userInfo: nil, repeats: true)
}
#objc func sixHourCountdown()
{
let timeStarted = UserDefaults.standard.object(forKey: "count6")
let timeStart = timeStarted as! Date
let diffComponents = Calendar.current.dateComponents([.hour, .minute, .second], from: compareTime, to: timeStart)
let hour = diffComponents.hour!
let minute = diffComponents.minute!
let second = diffComponents.second!
let timeRemaining = String(format: "%02d:%02d:%02d", hour, minute, second)
compareTime += 1
if hour == 0 && minute == 0 && second == 0 || timeStart < compareTime
{
button.setTitle("PRESS", for: .normal)
button.backgroundColor = .green
timer.invalidate()
}
else
{
button.setTitle("PRESS IN" + "\n\(timeRemaining)", for: .normal)
}
}
#objc func buttonTap()
{
if button.currentTitle != "PRESS"
{
button.backgroundColor = .red
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute:
{
button.backgroundColor = .yellow
})
}
if button.currentTitle == "PRESS" && button.backgroundColor == .green
{
UserDefaults.standard.set(currentTime, forKey: "count6")
let otherVC = OTHERVC()
self.navigationController?.pushViewController(otherVC, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupButtonTitle()

How to display current time on text label?

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)