Categories
JavaScript Answers

How to the Number of Seconds to a Time String in the hh:mm:ss Format with JavaScript?

Sometimes, we may want to convert the number of seconds elapsed to a time string in the hh:mm:ss format in our JavaScript app.

In this article, we’ll look at how to convert the number of seconds to a time string in hh:mm:ss format.

Create Our Own Function

We can create our own function to convert the number of seconds elapsed to a time string in hh:mm:ss format.

For instance, we can write:

const toHHMMSS = (numSecs) => {
  let secNum = parseInt(numSecs, 10);
  let hours = Math.floor(secNum / 3600).toString().padStart(2, '0');
  let minutes = Math.floor((secNum - (hours * 3600)) / 60).toString().padStart(2, '0');;
  let seconds = secNum - (hours * 3600) - (minutes * 60).toString().padStart(2, '0');;
  return `${hours}:${minutes}:${seconds}`;
}

console.log(toHHMMSS(1234))

In the toHHMMSS function, we parse the numSecs parameter into a number.

Then we compute the hours by dividing secNum by 3600.

Then we round it down to the nearest integer with Math.floor .

Then we call toString on it to convert it into a string.

And then we call padStart to pad the number string to 2 digits with a leading zero if necessary.

To compute the minutes , we subtract secNum by the hours multiplied by 3600 and divide the whole thing by 60.

We get the minutes after subtracting the hours.

And we round the number down to the nearest integer with Math.floor .

Then we pad it into a 2 digit string with padStart also.

Next, we compute the seconds by subtracting the hours and minutes converted to seconds from secNum .

Then we convert it to a string and call padStart on it to pad the string to 2 digits with a leading zero if necessary.

And finally, we return the hours , minutes , and seconds in a string.

Therefore, the console log should log:

'00:20:34'

Date.prototype.toISOString

We can call toISOString on the JavaScript date object to get a date string with the hours, minutes, and seconds.

To get the elapsed time, we just create a date with timestamp 0, then call setSeconds to set the timestamp to the elapsed seconds.

And then we can all toISOString to get the date string and extract the hours, minutes, and seconds part of the returned date string.

For instance, we can write:

const date = new Date(0);
date.setSeconds(1234);
const timeString = date.toISOString().substr(11, 8);
console.log(timeString)

We create a Date instance with timestamp 0.

Then we call setSeconds to set the seconds of the time.

And then we call toISOString to get a date string.

Then we call substr to extract the hours, minutes, and seconds substring.

Therefore, timeString is:

'00:20:34'

Conclusion

We can use math, date, and string methods to get the elapsed seconds into hh:mm:ss format easily with JavaScript.

Categories
JavaScript Answers

How to Initialize a JavaScript Date to a Particular Time Zone?

Sometimes, we may want to initialize a JavaScript date to a particular time zone.

The default time zone is UTC.

In this article, we’ll look at ways to initialize a JavaScript date into a particular time zone.

Add the Time Zone to the End of the Date String

We can add the time zone info to the end of the date string that we use to create the Date object.

For instance, we can write:

const d = new Date("2020-04-13T00:00:00.000+08:00");
console.log(d)

The +08:00 part means that the date string we have is 8 hours ahead of UTC.

So d is:

Sun Apr 12 2020 09:00:00 GMT-0700 (Pacific Daylight Time)

when we’re using a device set to the Pacific time zone.

Date.prototype.toLocaleString

The JavaScrip date object has the toLocaleString method to convert a date to a date string in the given time zone.

For instance, we can write:

const d = new Date("2020-04-13T00:00:00.000+08:00");
const dateStr = d.toLocaleString('en-US', {
  timeZone: 'America/New_York'
})
console.log(dateStr)

to do this.

We call toLocaleString on d with the locale as the first argument.

The 2nd argument is an object with the timeZone property set to 'America/New_York' so that we can return a date string in the New York time zone.

Therefore, dateStr is:

4/12/2020, 12:00:00 PM

which is the equivalent of the date and time we pass into the Date constructor in the New York time zone.

Getting the Hours

If we get the hours with getHours , then the hour returned will be the equivalent in the device’s time zone.

For instance, if we have:

const d = new Date("2020-04-13T00:00:00.000+08:00");
console.log(d.getHours())

The time in the string is midnight.

And the time zone is UTC +8.

So if we’re in the Pacific time zone, we get 9 since it’s Daylight Saving Time so it’s 7 hours behind UTC and 15 hours behind UTC +8.

Conclusion

We can initialize a date with the given time zone by adding the time zone information to the date string we use to create the Date instance in JavaScript.

Categories
JavaScript Answers

How to Convert JavaScript Map Keys to an Array?

JavaScript maps let us store key-value pairs easily in our code.

Sometimes, we may want to convert JavaScript map keys into an array.

In this article, we’ll look at how to convert JavaScript map keys into an array.

Array.from Method and Map.prototype.keys

We can call the Array.from with the keys method of a map to convert the keys of a map to an array.

The keys method return an iterator with all the keys.

And the Array.from method converts the iterator with keys into an array of keys.

For instance, we can write:

const map = new Map()
  .set('a', 1)
  .set('b', 2);
const keys = Array.from(map.keys());
console.log(keys)

We create a new Map instance to create a map.

Then we call set with the key and value that we want to set passed in in this order.

Next, we call Array.from with the return value of map.keys to return the iterator with the map keys to an array.

Therefore we get:

["a", "b"]

as the value of keys .

Spread Operator and Map.prototype.keys

Likewise, we can use the spread operator with the keys method to convert the iterator with keys to an array of keys.

For instance, we can write:

const map = new Map()
  .set('a', 1)
  .set('b', 2);
const keys = [...map.keys()];
console.log(keys)

And we get the same result for keys .

Conclusion

We can return an iterator with the map keys with the Map.prototype.keys method.

Then we can convert the iterator with keys to an array of keys either with the Array.from method or the spread operator.

Categories
JavaScript Answers

How to Declare Static Constants in ES6 Classes?

Sometimes, we may want to declare static constants in our JavaScript classes.

In this article, we’ll look at how to declare static constants in ES6 classes.

Add Getters in Our Class

To declare static constants in our ES6 classes, we can declare constants outside the class and add getters that return the constants in our class.

For instance, we can write:

const constant1 = 3,
  constant2 = 2;
class Example {
  static get constant1() {
    return constant1;
  }

  static get constant2() {
    return constant2;
  }
}

console.log(Example.constant1)
console.log(Example.constant2)

We declare constant1 and constant2 .

Then in the Example class, we create the constant1 and constant2 getters.

We add the static keyword before get so that we can make the static.

Then in the getter function, we return the constant1 and constant2 values respectively.

Likewise, we can write:

class Example {
  static get constant1() {
    return 3
  }

  static get constant2() {
    return 2
  }
}

Object.freeze(Example);
console.log(Example.constant1)
console.log(Example.constant2)

which is equivalent to what we have written above.

So when we log the values of Example.constant1 and Example.constant2 , we see 3 and 2 respectively.

Object.freeze

We can freeze the class to make the whole class immutable.

To do this, we write:

class Example {}
Example.constant1 = 3
Example.constant2 = 2
Object.freeze(Example);
console.log(Example.constant1)
console.log(Example.constant2)

We add our static properties with:

Example.constant1 = 3
Example.constant2 = 2

This works since classes are constructor functions, which are objects.

This also means we can use the Object.freeze method on Example to make the Example class immutable.

So we can log the values of the Example.constant1 and Example.constant2 properties and get their values.

We should see 3 and 2 respectively.

Conclusion

We can declare static constants in our JavaScript class by declaring static getters that returns constants declared outside the class.

Also, we can freeze the class with the Object.freeze method since it’s a regular object.

This makes the class immutable.

Categories
JavaScript Answers

How to Reject a Promise with the JavaScript async/await Syntax?

The async and await syntax lets us write promise code that runs sequentially very cleanly.

It lets us do everything that we do with regular promise code.

Sometimes, we may want to reject a promise in the async function.

In this article, we’ll look at how to reject a promise with the JavaScript async and await syntax.

Throw an Error

One way to reject a promise in an async function is to throw an error inside it.

For instance, we can write:

const fn = async () => {  
  try {  
    await Promise.resolve(1)  
    await Promise.reject('error')  
  } catch (error) {  
    throw new Error(error);  
  }  
}  
fn()

We create the fn async function that has some promise code.

In the try block, we call Promise.reject to invoke a rejected promise.

Then we throw an error within the catch block, which will catch the rejected promise.

The error value is the string we pass into the Promise.reject method.

So we should see the 'error' string logged in the console since we threw the error in the catch block.

Throwing an Error instance lets us see the stack trace of the error and the content.

We can also throw anything with the throw keyword.

So we can write:

const fn = async () => {  
  try {  
    await Promise.resolve(1)  
    await Promise.reject('error')  
  } catch (error) {  
    throw error;  
  }  
}  
fn()

to just throw the error itself without putting it into the Error constructor.

But then now the console won’t show the stack trace.

It’ll only show the error value.

Return a Rejected Promise

We can also return a rejected promise in our code.

For instance, we can write:

const fn = async () => {  
  await Promise.resolve(1)  
  return Promise.reject('error')  
}  
fn()

to return a rejected promise.

Then when we run the function, we’ll only see the value we pass into the Promise.reject method and no stack trace.

We can do the same thing with any other rejected promise.

Conclusion

There’re various ways we can use to reject a promise with the async and await syntax.