© Russ Ferguson and Keith Cirkel 2017
Russ Ferguson and Keith CirkelJavaScript Recipes10.1007/978-1-4302-6107-0_6

6. Dates and Times

Russ Ferguson and Keith Cirkel2
(1)
Ocean, New Jersey, USA
(2)
London, UK
 

Using the Date Object

Problem

You need to get date and time information.

Solution

You need to create an instance of the Date object. Depending on if you need the current time or some other time in the past or future, you may need to pass parameters to the constructor .

The Code

var now = new Date(); //returns todays date and time
console.log(now);
var fluxCapacitorDate = new Date('November 5, 1955');
console.log(fluxCapacitorDate); //returns the date with time being all 0’ meaning midnight of that day.
var infinityWarDate = new Date(2018, 4, 4);  //returns date at midnight
console.log(infinityWarDate);
var unixTimestamp = Date.now(); // returns numbers representing the current date in milliseconds
console.log(unixTimestamp);
Listing 6-1.
Creating Instances of the Date Object

How It Works

In order to work with dates, you need to make an instance of the Date object. Unlike the Math object, it is not static. If you want to work with the current date, you don’t need to pass any parameters. If you need a certain date, there are a few ways of passing what you need over.
The quickest way is to pass a string representing the date. The value should be able to be in a format that the Date.parse() can recognize. You could spell out the date like in the previous example. You can also pass over the date as a string without spelling out the month. In this case, it would look like “1955-5-5”. In either case, you can also pass the time inside the string. For example, adding hour, minutes, seconds, and milliseconds like this: 'November 5, 1955 03:24:00:00'.
You can also add each item as a number directly, comma-separated, including time. All time is based on the number of milliseconds since January 1, 1970 UTC.
JavaScript does not always format the date exactly the same in every browser. Some recommendations would be:
  • If you add hours, also add minutes, because not all browsers will parse with just hours.
  • Milliseconds seem to only get parsed in Chrome.
  • If possible, use the YYYY/MM/DD format.
  • Hyphens (-) work best in WebKit browsers but are trouble in Firefox and IE; use slashes (/) as an alternative.
  • Make sure the year is four numbers. For example, passing ‘1/1/16’ returns 1916-01-01 as the date in Firefox and IE.
  • Using UTC time works in more recent browsers, but may not be supported in older browsers. IE 9, for example, would not parse it correctly.

Getting Date and Time Information

Problem

Now that you have an instance of the Date object, you need to get date and time information.

Solution

A good portion of what you will need is built into the Date object. In a few instances, the results are zero-based, similar to getting the length from an array.

The Code

var now = new Date(); //returns todays date and time
 console.log(now.getDate()); //returns the day of the month from 1 to 31
 console.log(now.getDay()); //returns the day of the week its zero based like an array 0 - 6;
 console.log(now.getFullYear()); //returns the current year
 console.log(now.getHours()); //returns hours from 0-23
 console.log(now.getMonth()); //return month from 0-11
 //time information
 console.log(now.getSeconds()); //returns seconds from 0-59
 console.log(now.getTime()); //returns the amount of milliseconds since the first of January 1970
Listing 6-2.
Getting Date Information then Time Information

How It Works

There are a lot of methods that will give you most of the date or time information you need. In some cases, the values are treated similar to an array, being zero based. For example, running getMonth() if it’s January results in 0.
These methods can be put together to give your users things like the current date and time. Now you can do interesting things with this information.

Calculating User Age

Problem

You need to figure out a user’s age in years.

Solution

Create two date objects and subtract the current year if the birthday has not happened yet. This is also good for figuring out years from a certain date.

The Code

var dob = new Date("12/3/1979");
var today = new Date();
var years = today.getFullYear() - dob.getFullYear();
dob.setFullYear(today.getFullYear());
if(today < dob){
        years--;        
}
console.log(years);
Listing 6-3.
Create Two Date Objects and Subtract the Current Year if the Day Has Not Happed yet in a for Loop

How It Works

The first instance has the birthday you want to use. The second is the current date. The third variable calculates the current year from the year in question. This will give you the total amount of years. The reason for the if statement is in the case the birthday has not yet happened . If that’s the case, it will remove a year.

Using the HTML5 Date Input Field to Make a Date Object

Problem

You need to create a date object based on the HTML5 date input form field.

Solution

HTML5 offers a lot of new input field types. One type is date. Unfortunately, at the time of this writing it is not supported in Firefox, Safari, or IE 11, but there is date support in Microsoft Edge and Opera. Since it is part of HTML5, it is not unreasonable to expect it to work in these browsers soon. There are other ways of creating this effect. For our example, we still stick with what is native to the browser.
When you select a date and submit the form, JavaScript will create a date object and print out the date in a text field.

The Code

//HTML form
<form>
<label for="dateComponent">Choose a date:
       <input type="date" id="dateComponent">
</label>
<label for="dateResult">You picked:
       <input type="text" id="dateResult">
</label>
       <input type="submit" value="Choose a date" id="subtmitBtn">
</form>
//JavaScript
var submitBtn = document.getElementById('subtmitBtn');
    submitBtn.addEventListener('click', function(e){
        e.preventDefault();
var dateSelected = document.getElementById('dateComponent');
var dateArray = [];
if(dateSelected.value != ''){
       console.log(typeof dateSelected.value); //result is a string         dateArray = dateSelected.value.split('');
         for(var i = 0; i < dateArray.length; i++){
                if(dateArray[i] === '-'){
                        dateArray[i] = '/';
         }
          }
var formatedDate = new Date(dateArray.join(''));
document.getElementById('dateResult').value = (formatedDate.getMonth() + 1) + '-' + formatedDate.getDate() + '-' + formatedDate.getFullYear();                            
    }
});
Listing 6-4.
Getting the Date from the HTML5 Date Input

How It Works

In this example, you add an event listener to the Submit button. When the button is clicked, the first thing you do is run the preventDefault() method so the browser does not leave the current page.
An empty array called dateArray is created that will be used when a value is returned. After that, you check the value of the component dateSelected to see if it returned a value. If the user does not select a date, then it will return a blank string. If that is not the case, take the string and use the split method to turn it into an array and assign that array to dateArray. The reason for this is that the result that you get back (year-month-day) does not parse correctly when used as part of the date constructor. So here we just change the format by looping though the array and changing the format to (year/month/day). Our new array then is joined back into a string and used in the date constructor.
Finally, we take the date object and put the results into a text field. The getMonth method is zero based (0 is January), so we add 1 for display purposes.

Checking If Two Dates Are the Same

Problem

You need to compare two different date objects.

Solution

In this case, you are checking if they are equal, but it will return false if the times are different.

The Code

var date1 = new Date("March 19, 1990 03:30:00");
var date2 = new Date("March 19, 1990 04:30:00");
if(date1.getTime() == date2.getTime()){
    console.log('date are the same');  
}else{
    console.log('dates are different');
}
Listing 6-5.
Determining If Two Dates Are Equal

How It Works

Use the getTime() method to convert the time to numeric values that represent the amount of milliseconds since January 1, 1970. If these numbers match, then the time is the same. If you create a date object without specifying the time, by default the time will be midnight of that day. The time will show up as all 0s. In this case, even if the days are the same, you will not get a match. If the time does not matter, you can use the setHours() method and set hours, minutes, seconds, and milliseconds to 0 the make the comparison. This does not account for different time zones or daylight savings time.

Working with getTimezoneOffset

Problem

You need to figure out the offset between UTC and local time .

Solution

The date object has some built-in ways to convert date and time into different formats. It does not handle time zones or daylight savings time. There are ways of figuring out the difference or offset between the UTC and the local time zone. There are also libraries that specifically deal with date and time zone problems.

The Code

//Want to know what the offset between UTC time and my local time
var currentDate = new Date();
var offSet = currentDate.getTimezoneOffset() / 60; converts minutes to hours
console.log(offSet);
//check if we are on daylight savings time
var today = new Date();
function isDST(){
        var jan = new Date(today.getFullYear(), 0, 1);
        var jul = new Date(today.getFullYear(), 6, 1);
        return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
if(isDST() != today.getTimezoneOffset()){
        console.log('On DST');  
}else{
        console.log('Not On DST');      
}
Listing 6-6.
Working with UTC and Local Time

How It Works

The first example gives you the difference between UTC time and your local time in minutes. When you divide the number by 60, you then get the amount of hours the offset is. For example, if you live on the east cost of the United States the off set is 4 because of daylight savings time. Meaning that Coordinated Universal Time (UTC) is 4 hours ahead of Eastern Time in the United States. The result of the getTimezoneOffset() method could be positive if you are west of UTC or negative if you are east of UTC. This method does not account for daylight savings time.
With this information, you can figure out if your user is currently on daylight savings time. The second example creates two date objects . The first of the year and the first of July. These two dates should return different offsets. For example, New York returns -5 normally and -4 during daylight savings time. To figure out if you are currently on daylight savings time, you can compare the current local time offset with the larger of the two date objects by returning the larger number using the max() method . This is why it returns the larger of the two offsets. If the function returns the local offset and the number and they are different, then you are on daylight savings time.

Formatting Date and Time

Problem

You want to format dates, including language and time zone.

Solution

The date can be formatted not only by using methods like the getDate() method . It can also be formatted to use different languages. You can use toLocaleDateString, toLocaleDateSting, or the internationalization API. The locales, options, and internationalization API work with the latest desktop browsers and with Safari’s nightly build. Mobile support is only for Chrome for Android 26.

The Code

//format the date using toLocaleTimeString
console.log(currentDate.toLocaleDateString('ja-JP'));
console.log(currentDate.toLocaleDateString('ja-JP', {weekday: 'long', year:'numeric', month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'}))
new Intl.DateTimeFormat('ja-JP', { weekday: 'long', year:'numeric', month:'short', day:'numeric', hour:'2-digit', minute:'2-digit', timeZone:'Asia/Tokyo', timeZoneName: 'short'}).format(new Date(1975, 07, 19)); //returns 1975年8月19日火曜日 13:00 JST
new Intl.DateTimeFormat('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }).format(new Date(1975, 07, 19)); // returns Tuesday, August 19, 1975
Listing 6-7.
Using toLocaleDateString and ECMAScript Internationalization API

How It Works

Using toLocaleDateString or toLocaleTimeString , the first parameter is the locales that can be used. Some examples are en-GB for British English or ko-KR for Korean.
The second parameter outlines the format details. This parameter is optional. Here you can set things like the time zone that you want to use. The times zones must recognize UTC and it uses the runtime as the default. It also understands names from the IANA time zone database like Asia/Tokyo or America/New_York.
Other options include weekday, era, year, month, day, hour minute, second, and timeZoneName.
Using the internationalization API, you can format the date the same way as using the toLocale methods. In the constructor, you can set the local as the first parameter. The second parameter uses the same options object. After that, you can use the format method and pass the date object.

Calculating Days from a Certain Date

Problem

You need to figure out how much time has passed since a certain date.

Solution

Use the getTime() method and check if your date is greater than the start date and less than the end date.

The Code

var date1 = new Date('6/15/2016);
var date2 = new Date('6/19/2016');
// 86,400,000 milliseconds is the number of milliseconds in one day
var oneDayInMS = 1000 * 60 * 60 * 24;
// Calculate the difference in milliseconds
var differenceInMS = Math.abs(date1.getTime() - date2.getTime());
var days = Math.round(differenceInMS/oneDayInMS);
console.log(days);
Listing 6-8.
Calculating the How Many Days from a Certain Date

How It Works

You create two date objects like in similar examples. In this case , we also subtract the first date from the second by milliseconds. The result on its own would be a negative new number, which is why the equation is done inside the Math.abs() method . It will turn the number into a positive integer.
We also have a variable that is the amount of milliseconds in a day. It is expressed by 1000 milliseconds times 60 seconds, times 60 minutes, times 24 hours. This will give you 86,400,000 milliseconds. Divide the difference between the two days by the amount of milliseconds in a whole day and round to the next highest integer.

Checking If Your Date Is in a Range of Dates

Problem

You need to know if the date selected is within a specific range.

Solution

The abs method of the Math object will give you the non-negative number.

The Code

var startDate = new Date('2/5/1990');
var endDate = new Date('3/25/2013');
var selectedDate = new Date('12/3/2000');
if(selectedDate.getTime() > startDate.getTime() && selectedDate.getTime() < endDate.getTime()){
       console.log('In the range');
       }else{
       console.log('Not in the range');  
}
Listing 6-9.
Check If the Selected Date Is Within the Range of the Start Date and End Date

How It Works

The getTime() method returns time in milliseconds in UTC time (number of milliseconds since January 1, 1970). In this case, we are just testing If the date chosen is higher than the start time in milliseconds and lower than the end time in milliseconds. Both parts of the if statement need to be true for this example to work.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.5.57