iostimeswiftuialarmxcode11.1

How can I get current time in Swift (Xcode11.1)


I made simple alarm application. At Swift4 or when swift got main storyboard, I can get current time by using dateformatter. But now I got Xcode(v.11.1) and I can't use dateformatter. my code is very simple and I'm a beginner. if I wrote code this way I got 6 problems.

Consecutive declarations on a line must be separated by ';'

Expected '(' in argument list of function declaration

Expected '{' in body of function declaration

Expected 'func' keyword in instance method declaration

Expected declaration

Invalid redeclaration of 'dateFormatter()'

I know that it's going to be very simple problem for you I search google, docs even stack but I can't get any correct way to solve this problems.

import SwiftUI
import Foundation


struct Alarm_view: View {

let time = Date()
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:ss"
let stringDate = dateFormatter.string(from: time)


@State var selecttimes = Date()
@State var sound = 1
@State var currenttimes = NSDate()
@State var currenttimetext = Date()
@State var timetext = Date()


var body: some View {
    VStack {
        NavigationView{
            Form {
                Section {
                    DatePicker(selection: $selecttimes,displayedComponents: .hourAndMinute, label: { Text("tamest") })
                    Picker(selection: $sound, label: Text("alarm")) {
                        /*@START_MENU_TOKEN@*/Text("1").tag(1)/*@END_MENU_TOKEN@*/
                        /*@START_MENU_TOKEN@*/Text("2").tag(2)/*@END_MENU_TOKEN@*/
                        Text("3").tag(3)
                    }
                }
            }.navigationBarTitle(Text("alarm set"))
        }
        VStack {
            Button("start") {
                self.timetext = self.selecttimes


            }.foregroundColor(Color.black).offset(y:-5)
            Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
            Text("stop")
                .foregroundColor(Color.red)
        }
        }.offset(y: -10)
        Text("\(timetext)")
        Text("\(currenttimetext)")

    }
}

}
struct Alarm_view_Previews: PreviewProvider {
static var previews: some View {
    Alarm_view()
}
}

Solution

  • You should define the following code in function

        let time = Date()
        let timeFormatter = DateFormatter()
        timeFormatter.dateFormat = "HH:ss"
        let stringDate = timeFormatter.string(from: time)
    
    
        func getDate()->String{
         let time = Date()
         let timeFormatter = DateFormatter()
         timeFormatter.dateFormat = "HH:ss"
         let stringDate = timeFormatter.string(from: time)
         return stringDate
        }
    

    Hope this helps you in fixing issue