Categories
JavaScript Answers

How to Format a Date as an ISO-8601 String with Moment.js and JavaScript?

Sometimes, we may want to format a date into the IS0–8601 standard format and JavaScript.

In this article, we’ll look at how to format a date into an ISO-8601 string with moment.js and JavaScript.

The toISOString Method

Moment.js comes with the toISOString method to let us format dates to ISO-8601 format.

For instance, we can write:

console.log(moment(new Date(2021, 1, 1)).toISOString())

Then we get:

'2021-02-01T08:00:00.000Z'

as a result.

The format Method

The format method also lets us format a date to an ISO-8601 date string.

For instance, we can write:

import moment from "moment";
console.log(moment(new Date(2021, 1, 1)).format());

Then we get the same result as before.

Timezone Support

We can use the Moment Timezone library to add support for time zones.

Then we can set the time zone in our app and then use the toISOString method to convert the moment object to an ISO-8601 string.

For instance, we can write:

const moment = require("moment-timezone");
moment().tz("America/Los Angeles");
console.log(moment(new Date(2021, 1, 1)).toISOString(true));

Then the console log logs:

'2021-02-01T00:00:00.000-08:00'

as a result.

Parsing ISO-8601 Dates

We can parse ISO-8601 dates with moment.js

For instance, we can write:

import moment from "moment";
console.log(moment("2021-01-01", moment.ISO_8601));

We pass in a date string in ISO-8601 format.

And we pass in the moment.ISO_8601 constant to let moment know that the date string in the first argument is an ISO-8601 date.

Conclusion

We can create and parse ISO-8601 date strings with moment.js in our JavaScript code.

Categories
JavaScript Answers

How to Get a CSS Property Value of an Element with JavaScript?

Sometimes, we may want to get a CSS property value of an element with JavaScript.

In this article, we’ll look at how to get a CSS property value of an element with JavaScript.

Use the window.getComputedStyle Method

We can use the window,getComputedStyle method to get the computed CSS styles of an element.

For instance, if we have the following HTML:

<div style='height: 300px; overflow-y: auto'>

</div>

Then we can write the following JavaScript:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

const style = window.getComputedStyle(div);
const height = style.getPropertyValue('height');
console.log(height)

to add some content to the div.

We have the for loop to add 100 p elements into the div with document.createElement .

Then we set the textContent of each element to add some content.

And then we call div.appendChild to add the p elements as children of the div.

Next, we call window.getComputedStyle with the div to get a style object.

And then we can get the height property with:

const height = style.getPropertyValue('height');

And height is '300px' since we set it as such in the HTML.

Use the Element’s computedStyleMap Method

Also, we can use the computedStyleMap method that comes with elements to get the styles applied to the element.

For instance, we have the following HTML:

<div style='height: 300px; overflow-y: auto'>

</div>

And we can write the following JavaScript:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

const style = div.computedStyleMap();
const height = style.get('height');
console.log(height)

Everything above the last 3 lines is the same as before.

Then we call div.computedStyleMap to get a style object that we can use to get the styles.

And then we have:

const height = style.get('height');

to get the CSSheight property value of the div.

This time height should be:

{value: 300, unit: "px"}

The value and unit are separate properties in the returned object.

Conclusion

There’re a few ways we can use to get the CSS properties from an element with JavaScript.

Categories
JavaScript Answers

How to Embed an Auto-Playing YouTube Video in an Iframe with JavaScript?

Sometimes, we may want to embed an auto-playing YouTube video on our web page with JavaScript.

In this article, we’ll look at how to embed an auto-playing YouTube video in an iframe with JavaScript.

Embed Auto-playing YouTub Video

To embed an auto-playing YouTub video, we can write the following code:

<iframe width="420" height="345" src="https://www.youtube.com/embed/n4BSyc7ZLiE?autoplay=1" frameborder="0" allowfullscreen></iframe>

We add an iframe element with the width and height for the video.

In the src attribute, we have the YouTube video embed URL with the autoplay query parameter set to 1 to enable autoplay.

frameborder set to 0 removes the border around the iframe.

allowfullscreen lets us make the iframe full screen.

Conclusion

We can embed an auto-playing video in an iframe by setting the autoplay query parameter of the embed video URL to 1.

Categories
JavaScript Answers

How to Convert a String of Numbers to an Array of Numbers in JavaScript?

Sometimes, we have a string with a comma-separated list of numbers that we want to convert to an array of numbers.

In this article, we’ll look at how to convert a string of numbers to an array of numbers in JavaScript.

Using String and Array Methods

We can use the split method available with JavaScript strings to convert a string into an array of strings by splitting the string by a separator.

So we can use the split method to split the string into an array of strings by the commas.

So it’ll return an array of strings with the stuff between the commas.

Then we can call the array map method to map the split string array entries into numbers.

For instance, we can write:

const nums = "1,2,3,4".split(`,`).map(x => +x)
console.log(nums)

We call split with the comma to separate the string into an array with the number strings in it.

Then we call map with a callback that converts each entry to a number with the unary + operator.

Therefore, nums is [1, 2, 3, 4] as a result.

Instead of using the unary + operator, we can also use the parseInt function.

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => parseInt(x, 10))
console.log(nums)

parseInt takes 2 arguments.

The first argument is the value we want to convert to a number.

The 2nd argument is the base that we want the returned number to be in.

So 10 would convert x to a decimal number.

Therefore, we get the same result as before.

Another way to convert the strings to numbers is to use the Number function.

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => Number(x))
console.log(nums)

and we get the same thing.

Number always convert to decimal numbers so we don’t have to specify it.

There’s also the parseFloat function that converts a value to a floating-point number if we want to do that.

It takes the same argument as parseInt .

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => parseFloat(x, 10))
console.log(nums)

And we get the same result as before for nums .

Conclusion

We can convert a string of numbers to an array of numbers with some string, array and number functions.

Categories
JavaScript Answers

How to Get the Start and the End of a Day in JavaScript?

Sometimes, we may want to get the start and end of a day with JavaScript.

In this article, we’ll look at ways to get the start and end of a day with JavaScript.

Using Native Date Methods

One way to get the start and end of a day with JavaScript is to use native date methods.

We can use the setHours method to set the hours of a day to the start or end of a day.

For instance, we can write:

const start = new Date(2020, 1, 1, 1, 1);
start.setHours(0, 0, 0, 0);
console.log(start)

We create the start date with the Date constructor.

Then we call setHours with all zeroes to set the time of the date to midnight.

So start is:

Sat Feb 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)

if we’re in Pacific time.

Likewise, we can use setHours to set the hours, minutes, seconds, and milliseconds to the end of the date.

To do this, we write:

const end = new Date(2020, 1, 1, 1, 1);
end.setHours(23, 59, 59, 999);
console.log(end)

to create a date and set it to the end of the date by passing in a few arguments.

23 is the hours.

The first 59 is the minutes.

The second 59 is the seconds.

And 999 is the milliseconds.

Therefore, end is:

Sat Feb 01 2020 23:59:59 GMT-0800 (Pacific Standard Time)

after calling setHours .

Using Moment.js

Alternatively, we can use the moment.js library to return the start and end of a date.

For instance, we can write:

const start = moment(new Date(2020, 1, 1, 1, 1)).startOf('day');
console.log(start.toString())

to create a moment object with the moment function with a JavaScript native date object as its argument.

Then we call startOf with 'day' to return a moment object with the time set to the start of the day.

So we get:

Sat Feb 01 2020 00:00:00 GMT-0800

as the value of start.toString() if we’re in the Pacific time zone.

Likewise, we can use the endOf method to get the end of the date.

To do this, we write:

const end = moment(new Date(2020, 1, 1, 1, 1)).endOf('day');
console.log(end.toString())

We call endOf instead of startOf .

And then end.toString() returns Sat Feb 01 2020 23:59:59 GMT-0800 if we’re in the Pacific time zone.

We can also convert the time zone to UTC before call startOf and endOf with the utc method.

For instance, we can write:

const start = moment(new Date(2020, 1, 1, 1, 1)).utc().startOf('day');
console.log(start.toString())

const end = moment(new Date(2020, 1, 1, 1, 1)).utc().endOf('day');
console.log(end.toString())

to do the conversion.

Then start.toString() returns:

Sat Feb 01 2020 00:00:00 GMT+0000

And end.toString() returns:

Sat Feb 01 2020 23:59:59 GMT+0000

Conclusion

We can get the start and end of a date with JavaScript with native date methods or moment.js.