Holiday in Brazil!

Hey guys!

After an extenuating sprint, I’m back and it’s a religious holiday in Brazil!

At the sprint, I had a chance to help others developers to get things done! The things was very simple to me but, they seemed to be difficult to the junior ones!

So, maybe I help someone who needs the same results!

 

Countdown to a specific date using HTML 5 + Javascript + MVVM + Knockout.js!

Yes… we still use Knockout.js, and we love it!

The thing was very simple! The website get a future event info and must to show a countdown.

Let’s make it simple! I help you to start an Asp.net MVC project (I’m a C# developer…) but, we’ll use only the standards.

Step 1 – Creating the project

Create a folder (mine is CoolThings), right click on it and click: Open With Code (we’ll use the fantastic Visual Studio Code to do this).

Click Ctrl + ‘ to open the terminal and type “dotnet new mvc” and hit Enter!part 01 a

This command will create an Asp.Net MVC project on the opened folder.
part 01 b

If you want to test it, just type “dotnet run” and the app will start!
part 01 c

Open http://localhost:5000 and your server will be there!
part 01 d

Step 2 – Adding Knockout.js

An Asp.Net MVC project have only bootstrap and jquery on bower, so, we need to put the knockout on the dependencies!

Just write: “knockout”: “latest”step 2 a

At the terminal, run the command bower update and the knockout will be downloaded! Take a look:
step 2 b

Step 3 – Making Knockout ready to use

Guys, remember: this post is about dates and countdown, not an Asp.Net MVC project, so… let’s be pragmatic!

  1. Open the _Layout.cshtml page (located at ~/Views/Shared);
  2. Scroll to <environment exclude=”Development”>;
  3. Put the knockout reference near the close tag;
  4. Run the command dotnet run and check if the knockout is available.

step 3 a

Open the browser, hit F12 and check at “source” tab if you can see the knockout script.step 3 b

Yess! Let’s code!

Cleaning the mess! Let’s code!

Open ~/Views/Home/Index.cshtml and delete all the code, except the Razor code ViewData.code 01

Why? Run the application (dotnet run) and check! The Title must be Home Page and the page should be clear!code 01 b

The html code!

A div with 20px margin, two paragraphs, we need an input (to get the date data) and a span, that will recieve the result.

Open the browser and hit F5 (you don’t need to stop and start the application ;-))2017-10-12 (13)

You’ll see…2017-10-12 (14)

The Javascript!

This was easy, eh?! Let’s write some scripts! To be more simple, let’s code the ViewModel at the page, remember? Dates and a countdown, not MVVM, etc…

Quick explanation: by default, at the bottom of the layout page, we’ll find the code “@RenderSection(“scripts”, false)”, so… when we code “@section scripts { … }”, everything inside the curly braces will be rendered at that position on layout page.

In this case, at the bottom of the layout page. Look:

2017-10-12 (16)

Returning to our code, let’s put our scripts where they must to be: right above the </body> tag.2017-10-12 (15)

The script tag and we start to code our ViewModel!

The ViewModel expects a date, and, we put the code that makes the Knockout work: ko.applyBindings, that expects a ViewModel with the observables variables, functions, etc., and allows the “data-bind” attribute to do its “magic”! (read more at http://knockoutjs.com/documentation/observables.html).

2017-10-12 (17)

Let’s create our first observables!

The creation of the ‘self’ variable is a knockout pattern 😉 accept it!

The ‘theDate’ observable is initialized with the date passed on the ko activation and it will populate the input tag (next print…), and the result observable will write on span tag…

code observables

To bind the observable on our tags, we must to use a ko attribute: “data-bind”, so… you can grab more information here http://knockoutjs.com/examples/helloWorld.html!

OBS: There are no more “Wait…” written on span tag! The “wait…” text now initialize the result variable!2017-10-12 (19)

Save, go to the browser and hit F5!

Look! The date we passed to our ViewModel now populate the input field, and the “Wait…” text is there!2017-10-12 (20)

The countdown!

W3 School definition (https://www.w3schools.com/jsref/met_win_setinterval.asp):

The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).

So… the code putted in a “setInterval” will run on every second (in this code) til you stop it!

setInterval

Let’s have some fun! How about a counter that will count to 10 and then will stop the counter when it reaches 10?

  1. Write a variable outside the “setInterval” and initialize it with zero;
  2. Increment the variable;
  3. Log the variable;
  4. Update the observable;
  5. Check if the variable is greater than 10 (so you can see the number 10 for a second before the end message) and, if true, stop the ticker with the clearInterval function and write a message!

2017-10-12 (28)

Hit F12, click on console tab and hit F5!2017-10-12 (27)

Calculating the interval between dates!

Note that we’ll try to initialize a date (read more: https://www.w3schools.com/js/js_dates.asp) with the value of ‘theDate’ variable and that can be anything if we don’t the field isn’t masked, then if the value isn’t suitble to initialize the date, the result of the calculation between the dates will be a NaN (not a number).

If interval variable is NaN, we must stop the ticker, write a message and interrupt the code execution! The clearinterval stops the recurrency, not the code!

If the interval is negative (dates written as numbers, and the calculation produces this ‘kind of date format’ (in milliseconds), specifiy the number of milliseconds since January 1, 1970, 00:00:00) it means that the date given is earlier than today and we also must to stop the ticker, write a message and break the code execution!

Interrupt the code execution means write a ‘return’ command.

2017-10-12 (29)

Testing…

Writing an invalid date in the field. As the ticker was stoped, to make a new test you must to reload the page.2017-10-12 (30)

Writing a date earlier than today in the field. As the ticker was stoped, to make a new test you must to reload the page.
2017-10-12 (31)

Writing a future date. As the ticker doesn’t was stoped, to make a new test, simply write a new date.
2017-10-12 (32)

Finishing the code!

Well, remembering, the date in the interval variable is a number that represents the amount of milliseconds since January 1, 1970, 00:00:00 til the given date.

There is a weird behaviour with the javascript date constructor! It ALWAYS use your timezone to create a date object, so, in Brazil, new Date(‘2017-10-13’) is Thu Oct 12 2017 21:00:00 GMT-0300!!! Yesssss!!!! You want day 13 and javascript gives day 12 because, it subtracts 3 hours from 0h GMT.

The fix:

  1. Create the date;
  2. Add the subtracted hours this way: get the the hours from date (getHours()) and then, add the timezone offset (the getTimeZoneOffset() method returns the MINUTES – believe, not in milliseconds – to GMT, so, you must  devide by 60 to get the hours).

fix

After fix the weird behaviour, to get the amount of days from a date in milliseconds, we need to know how many milliseconds make a day!

Simple: 1000 milliseconds * 60 seconds * 60 minutes * 24 hours! Once discovered the number, simply divide the interval by this number and use the floor() method to get the days!

Hours? Take the module of the previous operation and divide by the amount of hours in milliseconds, and so on!

Clever, eh?!

To write the result, simple get a mask and replace some parts with the days, hours, etc. It’ll be cool if we can write

2017-10-12 (33)

Testing the final code!

Note the correct amount of hours and minutes for the 0h!

2017-10-12 (35)

Conclusion

Stay tuned! Simple things can get very difficult if you do not pay attention to the details.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s