Construct readable sentences from data.

Try making a readable sentence by using the Date object.

w3schools about javascript Date Object

The Date object is a javascript object that allows us to do manage how time is viewed in our app. Time is a complicated unit compared to the metric system where everything gets an extra digit when we round another multiple of ten. With dates we have years, months, weeks, days, hours, minutes, seconds, leap years, summer time and many time zones. All of this makes time complex to work with on a computer, but the built in javascript date object makes it much easier. Here is an example where we create a data object and then make a readable sentence from it. The aim of this tutorial is not to give you complete knowledge of the date object, but to let you try a few things it has to offer, hopefully making it easier to grasp how time and date works with javascript.

Before doing this you should have a basic understaning of javascript arrays and how they work. Here are two links to w3schoold and MDN about javascript arrays.

https://www.w3schools.com/js/js_arrays.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

So an array is a list containing several pieces of data. We can add data to the array, or retrieve it. In order to retrieve it we use an index specifying the position of the data in the array.

Open your console

Test the following code in the console by clicking F12 (Win) or Cmd + shift + i (Mac) on this page. Paste these arrays into the console so we can use them to make sentences later.

let weekDays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
let months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

Here are the same arrays with norwegian day- and week names if your audience is norwegian language. If you need an array in antorher language you can try making it yourself.

let ukeDager = ["søndag","mandag","tirsdag","onsdag","torsdag","fredag","lørdag"];
let mnd = ["januar","februar","mars","april","mai","juni","juli","august","september","oktober","november","desember"];

So we have defined the arrays and for the sake of practice we can retrieve information from the arrays using an index. Try the following pieces of code in the console:

weekDays[0];

weekDays[4];

months[0];

months[12];

months[3];

Notice how we retrieve data by typing the array name and then the index within square brackets. The code above is intended to give one error, did you get it? Do you see why the error occured? months[12] is referring to a month that is not in the array. There are 12 pieces of data (name of months) in the month array but since we retrieve the first element with 0 as an index the last element (December) has 11 as an index. This is counter intuituve to how we are used to reading dates but it is very relevant to how we use the date object.

Now make a Date object by pasting the following code to the console.

myDate = new Date();
console.log("The time is: "+myDate.getTime());

So here is what that code will return:

The time is: 1568326929732

That is a readable sentence but the time format is not the best. This number represents the amount of milliseconds from 1st of January 1970 until the myDate object was created with the code above. The Date object above now contains the time it was created. You can pass a time value to the date object upon creation, and you can also change the time later with the setTime() method or other methods.

Time as milliseconds since 1970 is very commonly used, for example in the earthquake feeds from USGS. The date object will make sense of this number for us and you can turn that information into readable sentences in any language you want. Paste the following code to

console.log("The month right now is: "+myDate.getMonth());

So, check what number is returned and compare that to the month you are currently in. At the time of writing this we are in September and the getMonth method returned 8, so that is one less than I would expect from a date. The following code uses the number returned by getMonth to pick an element from the months array and wraps that in a sentence.

console.log("It is "+months[myDate.getMonth()]+" now.");

This returns:

It is September now.

It is worth noting that the millisecond value of the date object operates in the UTC time zone, but when you retrieve information from the date object with a method such as getHours, getDate or getDay it is adjusted to your time zone.

The number returned by the getMonth method can be used add a weekday name to a sentence. Make arrays of month names and week day names in your own language and keep them handy. Here is a text string constructed from several pieces of data all coming from the date object. You can try to use these methods to make sentences in your own language. Once you have done it you can reuse it again and again and make variations.

console.log("Today is "+weekDays[myDate.getDay()]+" "+myDate.getDate()+". of "+months[myDate.getMonth()]+" and when this Date object was created it was "+myDate.getHours()+":"+myDate.getMinutes()+" o clock.");

This code is will construct a norwegian sentence using the norwegian arrays. Make sure you have declared the norwegian arrays before trying this in the console.

console.log("I dag er det "+ukeDager[myDate.getDay()]+" "+myDate.getDate()+" "+mnd[myDate.getMonth()]+" og dette dato objektet vart oppretta kl. "+myDate.getHours()+":"+myDate.getMinutes());

Seven past three should be 15:07, not 15:7

There is one problem with this. If the hour or minute value is less than 10 we will only get a single digit. You can try the following millisecond value in myDate to see what I mean:

myDate = new Date(1600866438629);

You can skip this part if you just want to use the result, in which case you simply copy paste the code at the bottom. Read on if you want to understand it.

The problem is that the getHours or getMinutes methods return a numerical value, so there is no leading zero to make it grammatically correct. Using the myDate we just declared with a specific time we can see this problem in action.

Now try any of the sentences above the ‘if it is easy..’ heading. You can see that the time in myDate is 15:07, but it is represented with a single digit so it says 15:7 and that is not grammatically correct. So we have to add what is known as an conditional operator to fix this. This is probably going to be a bit confusing. We are making what is know as a if else statement, but we will use a short version known as the conditional operator. you can read more about the conditional on MDN. We have to replace this:

myDate.getHours()

with this:

((myDate.getHours()<10?'0':'')+myDate.getHours())

The code above has the if else statement in short form. This basically says if the value returned by the getHours method is less than 10, like this:

myDate.getHours()<10?

That is immediately follow by two options separated by a colon.

'0':''

The way this conditional operator works is by using the first option if the conditional is true. In our case if the returned value is less than 10 the program will add a ‘0’ before the value from the function. If the value is ten or more is will use the second option whic is an empty string. The result is a string composed of ‘0’ + minutes’ or ”+ minutes.

Are you still reading?

The more classic way of making a conditional is to make a statement like this:

  if (myDate.getHours() < 10){
      return ('0' + myDate.getHours());
  } else {
      return ('' + myDate.getHours());
  }

This is probably a bit easier to read as it has words such as ‘if’ and ‘else’ that have a meaning in normal english, but essentially these codes do the same. The short version is more suited to be used constructing a string since it is short and makes less mess.

The quick solution

Here are the complete codes to make constructed sentences including the conditional operator to make the time values grammatically correct.

In English:

console.log("Today is "+weekDays[myDate.getDay()]+" "+myDate.getDate()+". of "+months[myDate.getMonth()]+" and when this Date object was created it was "+((myDate.getHours()<10?'0':'')+myDate.getHours())+":"+((myDate.getMinutes()<10?'0':'')+myDate.getMinutes())+" o clock.");

and Norwegian:

console.log("I dag er det "+ukeDager[myDate.getDay()]+" "+myDate.getDate()+". "+mnd[myDate.getMonth()]+" og dette dato objektet vart oppretta kl. "+((myDate.getHours()<10?'0':'')+myDate.getHours())+"."+((myDate.getMinutes()<10?'0':'')+myDate.getMinutes()));

If you want to learn more about the date object you can check all methods available on MDN.

Just the copy paste bits…

This is the meat of this article. Copy and paste the little bits below to get the information parts you need from the Date object.

The following code will output ‘Today is Thursday’ if the week day in the specific date is a Thursday. This code requires the array weekDays to be declared.

This will get the week day name from the week day array.

weekDays[myDate.getDay()];

Og denne koden vil gjere det same på norsk (In norwegian) :

ukeDager[myDate.getDay()];

This is the exact same method, but for month names

months[myDate.getMonth()]

Og såm navn på månad på norsk

mnd[myDate.getMonth()]

This is the code for showing time grammatically correct:

((myDate.getHours()<10?'0':'')+myDate.getHours())+"."+((myDate.getMinutes()<10?'0':'')+myDate.getMinutes())

All the codes above can be used to construct your own sentences containing these data. If that is done in a good way it should help your readers understand the data.