how to check if time is within a specific range in swift

前端 未结 11 1254
一整个雨季
一整个雨季 2020-12-05 03:24

Hi I am trying to check if the current time is within a time range, say 8:00 - 16:30. My code below shows that I can obtain the current time as a string, but I am unsure how

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 03:38

    also, the solution below looks short if i want to see if the time is in a specific range during day

    var greeting = String()
    let date     = Date()
    let calendar = Calendar.current
    let hour     = calendar.component(.hour, from: date)
    //let minutes  = calendar.component(.minute, from: date)
    let morning = 3; let afternoon=12; let evening=16; let night=22;
    
    print("Hour: \(hour)")
    if morning < hour, hour < afternoon {
        greeting = "Good Morning!"
    }else if afternoon < hour, hour < evening{
        greeting = "Good Afternoon!"
    }else if evening < hour, hour < night{
        greeting = "Good Evening!"
    }else{
        greeting = "Good Night"
    }
    print(greeting)
    

    i guess you could modify it, to check for example, if the months are in certain ranges too, e.g:

    sum = "Jan"
    win = "March"
    Spr = "May"
    Aut = "Sept"
    

    and continue from there...

提交回复
热议问题