So how can we do that? I'll clear my Console, but my variable d is still defined. So I'm going to type get, and that shows me a lot of methods that are available here. Date, Day, the FullYear, Hours, Milliseconds, whole bunch of stuff here. So let's take a look at getDate. Today is the 16th of June, and so that's the date. Likewise, if I wanted to get the Month, I need to call this with its parentheses, I get 5.
So I'll use getHours, and then getMinutes. Great. 14, 43. Let's switch back to the code and actually use these methods. Here I have d.toTimeString. We can change this to getHours, and then we can add a time separater here, and call this again, using getMinutes. If I save this, switch back and reload, now I have 14:46.
If I want to reset this to a 12-hour clock, I'll wrap this in parentheses to avoid confusion, and then subtract 12 from it. If I refresh, now it's 2:47. Now, of course, I don't necessarily always want to subtract 12, because before noon, the hours will be less than 12, and then I could end up with numbers like negative 2:47. That's not right. So let's make this work correctly. I'm going to calculate my hours separately, ahead of time. So I'll create a variable here called hours.
We'll set it to getHours. Then afterwards, I'm going to check if hours is greater than 12, and if it is, I'm going to subtract 12 from my value of hours. So I could say hours = hours - 12, and I can put this all on one line like this if I like, or if you find it more readable, you can do it like this, inside the curly braces. So hours = hours - 12, or I can rephrase this using the -= operator, which is similar to the += operator we've seen before.
So if hours is greater than 12, we'll lop off 12, and so we'll never see a 13 or an hour greater than 12. If you're thinking ahead here, you may be wondering what happens when the clock strikes midnight. That's another edge case that we'll be dealing with a little later on. And so now I'll put my hours in here, save the file, and switch back. Refreshing, you can see that now it's 2:52 in the afternoon. Great. That's working fine. So now you've seen some of the methods that are available on the Date object to give you different components of the time.
- Working with the DOM
- Creating maps with the Google Maps API