Learn MORE JavaScript on the ServiceNow Platform: Lesson 5 Exercise - Date and Time
Okay, exercise time for the Date
object is a two parter this time. So let's take a look. So for part one. Imagine that we want to know the date. And what would it be
if it was 30 days after today's date? I have a code snippet on the screen. Let me know what you think
is wrong with the code. I'll pause right here. And then we'll talk about
what is wrong with this code. Okay, we're back. So it's actually pretty easy to see what's
wrong with this code if you just run it. So I'm going to go ahead and run it
and you'll see that in 30 days from now, it's not the 52nd of December. It doesn't know to wrap that number
around for the new month. So we need to solve
for that. Okay. Part two to find the date of 30 days after today, how would you edit
this code that you can see on the screen to display the date as if it was 30 days
after today's date truly? Go ahead and pause right now. See what you want to do to edit this code
to figure that out. And then we'll come back
to see if we got the same thing. And we're back. Did you get the same thing as I have? All I had to do was add a plus 30 here
and that made it work. and you can actually kind of see
why it works this way. It's because instead of just taking
now get date plus 30 and treating it as its own number
floating in space, we're actually taking that number
and we're setting the date. And so internally for the date object,
it knows when it's trying to set the date, if it has a plus 30 next to it and knows to follow the calendar,
it's built into it. So that's why it works that way. And we can see if it works by taking
that code and putting it inside ServiceNow and running it. And you'll see instead of 52,
we now get the Friday, December 22nd, and today is November 22nd. So that is 30 days later. Perfect.
https://www.youtube.com/watch?v=AAQRG_DM0uw