Categories
JavaScript Answers

How to Get the Number of Days Between Two Dates in JavaScript?

We often have to get the number of days between 2 dates in our JavaScript apps.

In this article, we’ll look at how to get the number of days between 2 dates with JavaScript.

Using String and Date Methods

We can calculate the number of days between 2 dates with JavaScript by using native string and date methods.

For instance, we can write:

const parseDate = (str) => {
  const [month, day, year] = str.split('/');
  return new Date(year, month - 1, day);
}

const datediff = (first, second) => {
  return Math.round((second - first) / (1000 * 60 * 60 * 24));
}

const diff = datediff(parseDate("1/1/2000"), parseDate("1/1/2001"))
console.log(diff)

We have the parseDate function that takes str date string in MM/DD/YYYY format.

We parse it by splitting the date string with '/' as the separator.

Then we get the year , month and day by destructuring.

And we pass all that into the Date constructor to return a date object.

We’ve to subtract month by 1 to get the correct JavaScript month.

Then we calculate the date difference with the dateDiff method by subtracting the second by first .

When we subtract 2 dates, both dates will be converted to timestamps automatically before subtraction.

So we can subtract them directly.

And then we divide this by 1 day in milliseconds.

Finally, we round the division result with Math.round .

Now we can call all the functions we created to parse and get the date difference from the parsed dates.

And so we get diff is 366.

moment.js

We can use moment.js to get the difference between 2 dates easily.

For instance, we can write:

const start = moment("2000-11-03");
const end = moment("2001-11-04");
const diff = end.diff(start, "days")
console.log(diff)

We just pass the date strings into the moment function.

Then we call diff to get the difference between the moment date it’s called on and the moment date object we passed in.

The 2nd argument is the unit of the difference we want to return.

So diff is also 366 since the 2 dates differ by 366 days.

Conclusion

We can use native JavaScript string and date methods to compute the difference between 2 dates.

Also, we can use the moment.js library to make our lives easier.

Categories
JavaScript Answers

How to Format a Floating Point Number in JavaScript?

Oftentimes, we have to format a floating-point number into the format we want in JavaScript.

In this article, we’ll look at how to format a floating-point number into the format we want with JavaScript.

Math.round

We can use Math.round to round a number into the number of decimal places we want by multiplying the original number 10 to the power of the number of decimal places we want to round to.

Then we pass that number into Math.round , and we divide the rounded number by the same number we multiplied the original number with.

For instance, we can write:

const original = 123.456
const result = Math.round(original * 100) / 100;
console.log(result)

We multiply original by 100, which is 10 to the power of 2.

So we round to 2 decimal places.

And we divide by 100.

Then result is 123.46.

This also works if we also round to other numbers of decimal places.

For instance, we can write:

const original = 123.45678
const result = Math.round(original * 1000) / 1000;
console.log(result)

And result is 123.457.

Number.prototype.toFixed

We can call the toFixed method to return a string with the number rounded to the given number of decimal places.

For instance, we can write:

const original = 123.45678
const result = original.toFixed(3)
console.log(result)

Then result is ‘123.457’ .

3 is the number of decimal places to round to.

result is a string instead of number in the previous example.

This is the easier way to format a number to the number of decimal places we want.

Conclusion

We can format a floating-point number into the number of decimal places we want with Math.round or the number’s toFixed method.

Categories
JavaScript Answers

How to Detect a Touch Screen Device Using JavaScript?

Sometimes, we may need to detect a touch screen device with JavaScript.

In this article, we’ll look at how to detect a touch screen device with JavaScript.

Checking for the ontouchstart Method and maxTouchPoints

One way to check for a touch screen device is to check for the window.ontouchstart method and the navigator.maxTouchPoints property.

For instance, we can write:

const isTouchDevice = () => {  
  return (('ontouchstart' in window) ||  
    (navigator.maxTouchPoints > 0) ||  
    (navigator.msMaxTouchPoints > 0));  
}  
console.log(isTouchDevice())

We check all the items present for a touchscreen device with:

('ontouchstart' in window) ||  
(navigator.maxTouchPoints > 0) ||  
(navigator.msMaxTouchPoints > 0)

ontouchstart lets us assign a touch event listener to it that runs when we start touching the screen.

maxTouchPoints returns the number of touchpoints of the screen.

And navigator.msMaxTouchPoints is the Microsoft version of the maxTouchPoints property.

This is a cross-browser solution that works on most modern browsers.

The window.matchMedia Test

Also, we can use the window.matchMedia method to test whether a device has any touchscreen features present.

For instance, we can write:

const isTouchDevice = () => {  
  return window.matchMedia("(pointer: coarse)").matches  
}  
console.log(isTouchDevice())

We test whether the pointer: coarse CSS feature is present.

And if it is, we know the device the app is running on is a touch screen device.

Conclusion

We can test for various touch features of a device with JavaScript to check whether a device is a touch device in our JavaScript web app.

Categories
JavaScript Answers

How to Check if a JavaScript String Contains a Substring in a Case Insensitive Manner?

Sometimes, we may want to check if a substring is in a JavaScript string in a case-insensitive manner.

In this article, we’ll check if a JavaScript string has a substring in a case-insensitive manner.

String.prototype.toLowerCase and String.prototype.indexOf

We can convert both the string and the substring we’re checking for the lower case to check if a substring is in a JavaScript string is in a case-insensitive manner.

For instance, we can write:

const includes = 'ABCDE'.toLowerCase().indexOf("abc".toLowerCase()) !== -1  
console.log(includes)

We call toLowerCase on 'ABCDE' and 'abc' to convert them both to lower case.

And then we call indexOf to check if “abc”.toLowerCase() to if included in 'ABCDE' in a case-insensitive manner.

Since 'abc' is in 'ABCDE' when they’re compared in a case-insensitive manner, indexOf should return an index other than -1.

And so includes is true .

Case-Insensitive Regex Search

We can also do a case-insensitive regex search in our code.

For instance, we can write:

const includes = /abc/i.test('ABCDE')  
console.log(includes)

The i flag lets us search for a pattern in the string we pass into test in a case-insensitive manner.

And so includes is also true in this example.

Case-Insensitive Regex Search with RegExp Constructor

Alternatively, we can do a case-insensitive regex search with the RegExp constructor.

For instance, we can write:

const includes = new RegExp("abc", "i").test('ABCDE')  
console.log(includes)

to do the same as we did before.

String.prototype.toLowerCase and String.prototype.includes

We can also substitute the indexOf method in the first example with includes .

Using the includes method, we don’t have to compare against -1.

Instead, we get true if the substring is included in a string and false otherwise.

So we can write:

const included = 'ABCDE'.toLowerCase().includes("abc".toLowerCase())  
console.log(included)

We convert them both the string and substring to lower case as usual, but we use includes to check if the substring we pass into includes is included in 'ABCDE' .

And so we should get the same result as before.

String.prototype.toLocaleLowerCase and String.prototype.includes

If we’re checking a JavaScript substring with a string that has text other than English, we may want to use the toLocaleLowerCase method since it works with non-English locales.

For instance, we can write:

const included = 'ABCDE'.toLocaleLowerCase().includes("abc".toLocaleLowerCase())  
console.log(included)

And we get the same result as before.

Conclusion

We can use various string or regex methods to check whether a substring is included in a JavaScript string in a case insensitive manner.

Categories
JavaScript Answers

How to Initialize a JavaScript Date to Midnight?

Sometimes, we may want to set a JavaScript date to midnight.

In this article, we’ll look at how to initialize a JavaScript date to midnight.

Date.prototype.setHours

We can use the setHours method to set the hour of the date to midnight.

For instance, we can write:

const d = new Date();  
d.setHours(0, 0, 0, 0);  
console.log(d)

We call setHours with the hours, minutes, seconds, and milliseconds all set to 0 to set the date d to midnight of the same date as the original date d .

The change mutates the d object.

So we see that d is midnight of the current date from the console log.

To set a date to tomorrow’s midnight, we can write:

const d = new Date();  
d.setHours(24, 0, 0, 0);  
console.log(d)

The first argument, which is the hours argument, is 24 instead of 0.

And from the console log, we should see that the date is the next day midnight.

If we want to make a copy of the date, we can pas the date to the Date constructor:

const d = new Date(new Date().setHours(0, 0, 0, 0));  
console.log(d)

Date.prototype.setUTCHours

If we want to work with UTC times, we can use the setUTCHours method to set a time to midnight.

For instance, we can write:

const d = new Date();  
d.setUTCHours(0, 0, 0, 0);  
console.log(d)

to set a date to midnight UTC.

moment.js

The moment.js library lets us set a date to midnight with the startOf method.

For instance, we can write:

const d = moment().startOf('day');  
console.log(d)

We call startOf with 'day' to set the moment object’s date-time to midnight of the same date that the moment date is on.

Conclusion

We can set a JavaScript date to midnight with native JavaScript date methods.

Also, we can use moment.js to do the same thing.