Categories
Day.js

Manipulating Dates with Day.js — Parsing and Validation

Day.js is a JavaScript library that lets us manipulate dates in our apps.

In this article, we’ll look at how to use Day.js to manipulate dates in our JavaScript apps.

Parsing Date to UTC Date

We can use the utc plugin to parse a date into a UTC date.

For instance, we can write:

const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");

dayjs.extend(utc);
const dt = dayjs.utc().format();
console.log(dt);

to import the Day.js with the utc plugin.

Then we can use the plugin by writing:

dayjs.extend(utc);

Now we can call the dayjs.utc method to create a date object with the current date and time in UTC.

Clone a Date

We can clone a Day.js date object with the clone method.

For instance, we can write:

const dayjs = require("dayjs");
const a = dayjs();
const b = a.clone();
console.log(a, b);

We call dayjs to create date object a .

Then we call clone on a and assign it to b to make b a clone of a .

Validation

To validate a date, we can use the isValid method.

It returns true if the date is valid and false otherwise.

For instance, we can write:

const dayjs = require("dayjs");
const isValid = dayjs().isValid();
console.log(isValid);

We call isValid on a Day.js date object.

Since we called in a valid date, isValid is true .

Conclusion

Day.js is a JavaScript library that lets us manipulate dates in our apps.

Categories
Day.js

Manipulating Dates with Day.js — Parsing

Day.js is a JavaScript library that lets us manipulate dates in our apps.

In this article, we’ll look at how to use Day.js to manipulate dates in our JavaScript apps.

Parsing JavaScript Native Date Objects

We can pass in native JavaScript date objects as an argument of the dayjs function.

To do this, we write:

const d = new Date(2020, 8, 18)
const dt = dayjs(d)
console.log(dt)

Parsing Plain JavaScript Objects into Dates

To parse plain JavaScript objects into dates, we can use the objectSupport plugin.

For instance, we can write:

const dayjs = require("dayjs");
const objectSupport = require("dayjs/plugin/objectSupport");

dayjs.extend(objectSupport);
const dt = dayjs({
  year: 2020,
  month: 3,
  day: 5,
  hour: 15,
  minute: 10,
  second: 3,
  millisecond: 123
});
console.log(dt);

We import the dayjs and dayjs/plugin/objectSupport modules to add the day.js library with the objectSupport plugin.

Then we add:

dayjs.extend(objectSupport);

to add the objectSupport plugin.

Now we can pass in an object into the dayjs function to parse it into a date.

Parsing JavaScript Array into Dates

Day.js also comes with the ArraySupport plugin that lets us parse an array of numbers into dates.

For instance, we can write:

const dayjs = require("dayjs");
const arraySupport = require("dayjs/plugin/arraySupport");

dayjs.extend(arraySupport);
const dt = dayjs([2020, 1, 14, 15, 25, 50, 125]);
console.log(dt);

to import the Day.js and arraySupport library respectively in the first 2 lines.

Then we add:

dayjs.extend(arraySupport);

to add the arraySupport plugin.

Now we can pass in an array into the dayjs function to parse the array into a date.

The order of the numbers in the array is year, month, day of the month, hour, minutes, seconds, and milliseconds.

Conclusion

Day.js is a JavaScript library that lets us manipulate dates in our apps.

Categories
Day.js

Getting Started with Manipulating Dates with Day.js

Day.js is a JavaScript library that lets us manipulate dates in our apps.

In this article, we’ll look at how to use Day.js to manipulate dates in our JavaScript apps.

Installation

We can install Day.js for Node.js or TypeScript apps by running:

npm install dayjs

If we use it in our TypeScript project, then we must add the following to compiler options to tsconfig.json :

{  
  "compilerOptions": {  
    "esModuleInterop": true,  
    "allowSyntheticDefaultImports": true,  
  }  
}

If we want to use it in the browser, we can add the script tag version of it with:

<script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>

Parsing Dates

We can create a Day.js date object with the dayjs function:

const now = dayjs()  
console.log(now)

This creates a Day.js date object with the current date and time.

We can also pass in a date string into the dayjs function:

const dt = dayjs('2020-04-04T16:00:00.000Z')  
console.log(dt)

And dt is a Day.js object with the given date.

We can also specify the date string’s format when we’re parsing it:

const dt = dayjs('05/02/20 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z')  
console.log(dt)

Timestamps can also be parsed into a Day.js date object:

const dt = dayjs(1318781876406)  
console.log(dt)

To parse a date from the timestamp converted to a number of seconds, we can use the unix method:

const dt = dayjs.unix(1318781876.721)  
console.log(dt)

Conclusion

Day.js is a JavaScript library that lets us manipulate dates in our apps.

Categories
React Answers

How to Add a Click Handler to the Body Element from within a React Component?

Sometimes, we want to add a click handler to the body element from within a React component.

In this article, we’ll look at how to add a click handler to the body element from within a React component.

Add a Click Handler to the Body Element from within a React Component

To add a click handler to the body element from within a React component, we call the addEventListener method on document.body in the useEffect hook callback to starting listening to clicks on the body element when the component loads.

For instance, we can write:

import React, { useEffect } from "react";
export default function App() {
  useEffect(() => {
    const onClick = () => {
      console.log("body clicked");
    };
    document.body.addEventListener("click", onClick);

    return () => {
      document.body.removeEventListener("click", onClick);
    };
  }, []);

  return <div>hello world</div>;
}

to call the useEffect hook with a callback that calls document.body.addEventListener with 'click' and onClick to add the onClick function as the event listener for click events emitted from the body element.

Also, we return function that calls removeListener to remove the body click listener when the component is unmounted.

And we pass in an empty array as the 2nd argument of useEffect to run the useEffect callback only when the component mounts.

Now when we click on the body element, we should see 'body clicked' logged in the console.

Conclusion

To add a click handler to the body element from within a React component, we call the addEventListener method on document.body in the useEffect hook callback to starting listening to clicks on the body element when the component loads.

Categories
React Answers

How to Use the marked Markdown Library in React?

Sometimes, we want to use the marked Markdown library in our React app.

In this article, we’ll look at how to use the marked Markdown library in our React app.

Use the marked Markdown Display Component in React

To use the marked Markdown display component in our React app, we just call, the marked function that comes with the marked library to convert the Markdown string into an HTML string.

Then we can render the HTML string with dangerouslySetInnerHTML .

For instance, we can write:

import React from "react";
import marked from "marked";
export default function App() {
  const getMarkdownText = () => {
    const rawMarkup = marked("This is _Markdown_.", { sanitize: true   });
    return { __html: rawMarkup };
  };

  return <div dangerouslySetInnerHTML={getMarkdownText()} />;
}

We create the getMarkdownText function to convert the “This is _Markdown_.” Markdown string into an HTML string with the marked function.

And we set sanitize to true to escape any special characters.

Then we set the dangerouslySetInnerHTML prop of the div to the HTML string returned by the getMarkdownText function.

Conclusion

To use the marked Markdown display component in our React app, we just call, the marked function that comes with the marked library to convert the Markdown string into an HTML string.

Then we can render the HTML string with dangerouslySetInnerHTML .