Categories
JavaScript Answers

How to Convert UTC Date Time to Local Date Time?

Sometimes, we may want to convert a UTC date-time to a local date-time in our JavaScript apps.

In this article, we’ll look at how to convert UTC date-time to local date-time.

Add UTC after the Date String and Pass the String into the Date Constructor

One way to convert UTC date time to a local date-time is to just add the 'UTC' suffix to the date-time string.

Then we pass it into the Date constructor.

For instance, we can write:

const date = new Date('6/29/2021 4:52:48 PM UTC');
console.log(date.toString())

Then if we’re in the Pacific Time zone, we get:

Tue Jun 29 2021 09:52:48 GMT-0700 (Pacific Daylight Time)

logged.

The conversion is done automatically to local time as we can see.

Add Z after the Date String and Pass the String into the Date Constructor

The Z suffix is the same as UTC for setting a date-time to UTC.

We can attach this suffix to an ISO-8601 date-time since it is part of the standard.

For instance, we can write:

const date = new Date('2021-06-29T16:52:48.000Z');
console.log(date.toString())

Then we get:

Tue Jun 29 2021 09:52:48 GMT-0700 (Pacific Daylight Time)

as a result if we’re in Pacific Time.

Call getTimezoneOffset Method to Convert the Date Time to a Local Date Time

We can call getTimezoneOffset on a JavaScript date offset to get the time difference UTC and the local time zone in hours.

For instance, we can write:

const date = new Date('2021-06-29T16:52:48.000');
const newDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000);
console.log(newDate)

We call getTime to get the timestamp for the date we want to convert.

Then we add the timezone offset in milliseconds we create with:

date.getTimezoneOffset() * 60 * 1000

Then we get the time zone offset and divide it by 60 to get the offset in hours.

And then we get:

Tue Jun 29 2021 02:52:48 GMT-0700 (Pacific Daylight Time)

as a result.

Conclusion

We can convert a UTC date-time into a local date-time with various date methods.

Categories
JavaScript Answers

How to Get the Loop Counter or Index Using for-of Loop in JavaScript?

The for-of loop is an easy-to-use loop that comes with JavaScript that lets us loop through arrays and iterable objects easily.

However, there’s no way to get the index of the element being looped through with it directly.

In this article, we’ll look at how to get the loop counter or index with the for-of loop in JavaScript.

Array.prototype.forEach

One way to get the index while iterating through an array is to use the forEach method.

We can pass in a callback with the index of the item being looped through in the 2nd parameter.

So we can write:

const arr = [565, 15, 642, 32];
arr.forEach((value, i) => {
  console.log('%d: %s', i, value);
});

We call forEach with a callback that has the value with the value in arr being iterated through.

i has the index of value .

And so we get:

0: 565
1: 15
2: 642
3: 32

Array.prototype.entries

JavaScript arrays also have the entries method to return an array of arrays with the index of the item and the item itself.

For instance, we can write:

const arr = [565, 15, 642, 32];
for (const [i, value] of arr.entries()) {
  console.log('%d: %s', i, value);
}

We destructure the index and value from the array entry and then we log both values with the console log.

So we get:

0: 565
1: 15
2: 642
3: 32

as a result.

Conclusion

There are several ways we can use to loop through an array and access the index and the value of the entry during each iteration.

Categories
JavaScript Answers

How to Extend the JavaScript Error Constructor?

To throw errors in our JavaScript apps, we usually through an object that’s the instance of the Error constructor.

In this article, we’ll look at how to extend the JavaScript Error constructor with our own constructor.

Create Our Own Constructor Function

One way to extend the built-in Error constructor is to create our own constructor that gets data from the Error constructor.

For instance, we can write:

function MyError(message) {
  this.name = 'MyError';
  this.message = message;
  this.stack = (new Error()).stack;
}
MyError.prototype = new Error();
throw new MyError('error occurred')

We create the MyError constructor that takes the message parameter.

We set message as the value of the message property.

And we get the stack trace from the stack property of the Error instance.

We set MyError.prototype to a new Error instance so that a MyError instance is also an Error instance.

In the constructor, we set the name which will be logged when an error is thrown.

Then we throw a MyError instance with the throw keyword.

Once the error, is thrown, we should see it in the log.

And if we log myError instanceof Error and myError instanceof MyError , we should see that both are true since we set MyError.prototype to a new Error instance.

Use the Class Syntax and extends Keyword to extend the Error Constructor

The class syntax is added to ES6 so that we can create constructors that inherit constructors easily.

However, underneath the syntactic sugar, prototypical inheritance is still used as we have in the previous example.

To extend the Error constructor, we write:

class MyError extends Error {
  constructor(message) {
    super(message);
    this.name = 'MyError';
  }
}

const myError = new MyError('error occurred')
console.log(myError instanceof Error)
console.log(myError instanceof MyError)
throw myError

We create the MyError class with the extends keyword to create a subclass of the Error class.

The constructor takes the message parameter and we pass that into the Error constructor by calling super .

We also set our own name property in the constructor.

And then we instantiate the MyError class the same way as before.

And if we use the instanceof operator on Error and MyError , we see that they’re both true .

When we throw an error, we see the message as we did before.

Conclusion

We can use regular prototypical inheritance or the class syntax to create our own constructor that inherits data from the Error constructor.

Categories
JavaScript Answers

How to Listen for Changes to HTML Elements with the contenteditable Attribute with JavaScript?

Elements with the contenteditable attribute added to it lets users edit the content inside the element.

Sometimes, we may want to listen for change events that are made to the element.

In this article, we’ll look at how to listen for changes triggered in elements that have the contenteditable attribute applied.

Listen to the input Event Emitted by the Element

When we change the content of an element that has the contenteditable attribute added, then input event will be emitted.

Therefore, we can listen to the input event of the element to listen for changes in its content.

For instance, we can write the following HTML:

<div contenteditable>
  hello world
</div>

And then we can add an event listener with the addEventListener with:

const div = document.querySelector("div")
div.addEventListener("input", (e) => {
  console.log(e);
}, false);

When we change the content in the div, we’ll see the input event listener run.

We can get the element’s attributes and styles with the e.target property.

The e.timestamp property is the time in milliseconds at which the event is created.

MutationObserver

We can also use the MutationObserver to watch for changes to the content of an element.

This is because it can listen for changes in the DOM, including any content changes in an element.

For instance, we can write:

const div = document.querySelector("div")
const observer = new MutationObserver((mutationRecords) => {
  console.log(mutationRecords[0].target.data)
})
observer.observe(div, {
  characterData: true,
  subtree: true,
})

and keep the HTML the same.

We pass in a callback with the mutationRecords object to get the mutation records.

chartacterData set to true means we watch for text content changes.

And subtree set to true means we watch for the element’s DOM subtree changes.

We get the latest content of the div with the mutationRecords[0].target.data property.

Conclusion

We can watch for changes of the content of an HTML with the contenteditable attribute applied with the MutationObserver or listen to the input event of the element.

Categories
JavaScript Answers

How to Watch for DOM Changes with JavaScript?

Sometimes, we may want to watch for changes in the DOM in our web app.

In this article, we’ll look at how to watch for changes in the DOM with JavaScript.

MutationObserver

One way to watch for DOM changes in our JavaScript web app is to use the MutationObserver constructor.

For instance, we can write:

const observer = new MutationObserver((mutations, observer) => {
  console.log(mutations, observer);
});

observer.observe(document, {
  subtree: true,
  attributes: true
});

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

(async () => {
  for (let i = 0; i < 5; i++) {
    const p = document.createElement('p')
    p.textContent = 'hello'
    document.body.appendChild(p)
    await sleep(1000)
  }
})();

to create the MutationObserver instance with a loop to append child elements to the body within the async function.

We insert a new p element after 1 second 5 times.

We pass in a callback into the MutationObserver constructor that runs when the DOM changes.

Then we call observe on the element that we want to observe changes for.

subtree set to true means that we watch for child element changes.

attributes set to true means we watch for element attribute changes.

Other options include:

  • childList — set to true to observe the target’s children
  • characterData— set to true to observe the target’s data
  • attributeOldValue— set to true to observe the element’s attribute’s value before the DOM change
  • characterDataOldValue— set to true to observe the target’s character data before a change is made
  • attributeFilter — set to the attribute’s local names to be observed.

The mutations parameter has a bunch of properties that have the changes applied.

The mutations.target property has the target element that’s changed.

mutations.target.lastChild has the bottommost child node in the element being watched.

mutations.target.lastElementChild has the bottommost child element node in the element being watched.

Listen to the DOMSubtreeModified Event

Another way to listen for DOM strucuter changes is to listen to the DOMSubtreeModified event.

For instance, we can write:

document.addEventListener('DOMSubtreeModified', (e) => {
  console.log(e)
})

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

(async () => {
  for (let i = 0; i < 5; i++) {
    const p = document.createElement('p')
    p.textContent = 'hello'
    document.body.appendChild(p)
    await sleep(1000)
  }
})();

to add an event listener for the document’s DOMSubtreeModified event.

The e parameter is an MutationEvent object.

The e.target property has the element that’s changed.

e.path has the path to the element that’s changed as an array of elements leading to the changed element.

e.children has an HTMLCollection object with the elements changed.

Conclusion

We can use the MutationObserver and the DOMSubtreeModified event to listen for changes to the DOM.