Rohith Vishwajith
Rohith Vishwajith

Reputation: 75

Convert hours form 12 hour time to 24 hour time Swift and save as an integer

I want to convert my variable for hours which is an integer into a 24 hour time system (for example, if it is 01:05:13 PM, hours will be saved as 13, minutes will be saved as 5, and seconds will be saved as 13) so that I can use it for some math later in my code to fid some differences on a scheduling app I am working on. This is my first app and I couldn't find an answer to this anywhere else so thanks for your help! Another way this code could work is getting the amount in seconds since the day has begun, if anyone knows how to do that, it would be greatly appreciated! This is my function for getting the time and saving it as three different integers for hours, seconds, and minutes:

@IBAction func setTime() {

    var date = NSDate()
    //pickTimes()
    var calendar = NSCalendar.current
    calendar.timeZone = TimeZone(identifier: "UTC")!
    var currentHour = calendar.component(.hour, from: date as Date) + 5
    let currentMinutes = calendar.component(.minute, from: date as Date)
    let currentSeconds = calendar.component(.second, from: date as Date)
    timeText.text = ("\(currentHour):\(currentMinutes):\(currentSeconds)")
}

Upvotes: 1

Views: 1439

Answers (1)

rmaddy
rmaddy

Reputation: 318814

  1. calendar.component(.hour, from: someDate) already gives you the time of day in 24 hour time so there's nothing else to do to solve your question.
  2. Not sure why you are adding 5 to the hour. You set the timezone to UTC so the date will be treated as the UTC timezone. Then you add 5 to that result. That's kind of strange. If you just want the current hour in the user's locale timezone, don't change the calendar's timezone and don't add 5 to the hour.
  3. Don't use NSDate or NSCalendar. This is Swift. Use Date and Calendar.

Updated code:

@IBAction func setTime() {
    var date = Date()
    //pickTimes()
    var calendar = Calendar.current
    var currentHour = calendar.component(.hour, from: date)
    let currentMinutes = calendar.component(.minute, from: date)
    let currentSeconds = calendar.component(.second, from: date)
    timeText.text = ("\(currentHour):\(currentMinutes):\(currentSeconds)")
}

But it would be simpler to use a DateFormatter and set the timeStyle to .medium or maybe .long and format Date() into a string. This will give a properly localized time string.

Upvotes: 3

Related Questions