This practice will be retired on May 31, 2020.
Solution: Formatting Time2:41 with Pasan Premaratne
Okay, so your task was to take this time in seconds, and convert that to 0:00 a formatted string that showed those seconds in hours, minutes, and seconds. 0:04 Now this is a bit tricky, but it all involves operators and 0:09 the correct precedents. 0:12 So first, we need to get the hours value out of this time component. 0:14 And the way we do that is by dividing the total time by the number 0:17 of seconds in an hour, so 3,600. 0:22 Because this is an integer value when we do this division, even though we get 0:24 a decimal value because it doesn't evenly divide here, at least in this case, 0:29 the compiler, Swift, just gets rid of all the values after the decimal point. 0:34 So we know that we have 664 hours with some amount of 0:38 time remaining when we divide by the number of seconds. 0:42 So that's how we got the hours component out. 0:47 For the minutes, this is the trickiest part. 0:50 For the minutes, we first want to see, once we figure out how many seconds there 0:53 are or how many hours there are in this total value, what time is remaining? 0:58 So essentially over here, when the decimal values got cut off, 1:03 what were those decimal values, and how many seconds were those? 1:06 And we can do that easily by using the modular operator. 1:09 So when we do time % 3600, that operation defines how many 1:13 3600s are there In the total time, and then gives us the remainder. 1:17 So that remainder is the amount of seconds left after we deduct the hours component. 1:23 Once we do that, we want it in minutes, so 1:29 we simply divide it by 60 to get it in minutes which is 5. 1:32 And then those are even number of minutes, because again, 1:35 here it's going to discard the remainder because this is an integer division. 1:38 So finally, to get any remaining seconds value, we do time. 1:43 And then using the percent sign, we get the remainder of finding out how many 1:47 seconds are there in this complete time component. 1:52 And when we do that we get 24. 1:55 So if I were to bring a calculator, or let me just write it out here, so 1:56 if I were to do, you'll see that in our printed string, 2:01 it says this is 664 hours, 5 minutes, 24 seconds. 2:04 And we did that final part pretty easily using string interpolation. 2:08 But if I were to do, for example, 664, 2:12 that's hours, so in minutes, and then in seconds. 2:16 To that we'll add 5 minutes in seconds and then 24 seconds. 2:20 And you'll see that the final value is exactly 2:26 the same as the value we started out with. 2:30 So keep this formula in mind because this is something you'll be doing fairly 2:35 often, okay? 2:38 On to the next exercise. 2:39
You need to sign up for Treehouse in order to download course files.Sign up