Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active October 30, 2023 12:30
Show Gist options
  • Save acidtone/232d9c9a0997692483fca51b6f624a61 to your computer and use it in GitHub Desktop.
Save acidtone/232d9c9a0997692483fca51b6f624a61 to your computer and use it in GitHub Desktop.
npm: install DayJS as a dependency

Activity: Install DayJS using npm

The goal of this activity is to:

  1. Install the dayjs package.
  2. Import the package into a node script.
  3. Output some fancy dates!

Prerequisites

Instructions

  1. Navigate to your project directory using your terminal.

  2. Install the dayjs package with the following command:

    $ npm install dayjs
    • Note that you can also use the shorter npm i dayjs command. npm i and npm install are the same command.
    • You will often see examples using the --save flag to download packages to node_modules. This is now default and no longer needed.
  3. You can now import dayjs in your Node application:

    import dayjs from 'dayjs'
    • Note: Not all packages are imported the same way. Check the package's documentation for proper use.
  4. Try logging some fancy dates to the console. Checkout the DayJS documentation or search for examples.

See included files for example of use:

  • now.js
  • diff.js
  • mars.js
import dayjs from 'dayjs'
const date1 = dayjs("2019-14-05");
const date2 = dayjs("2018-06-25");
// Difference in seconds
let df1 = date1.diff(date2);
console.log(df1);
// Difference in months (rounded)
let df2 = date1.diff(date2, "month");
console.log(df2);
// Difference in months (floating point)
let df3 = date1.diff(date2, "month", true);
console.log(df3);
// Difference in days
let df4 = date1.diff(date2, "day");
console.log(df4);
// Difference in weeks
let df5 = date1.diff(date2, "week");
console.log(df5);
import dayjs from 'dayjs'
let marsPerseverance = dayjs('2021-02-18');
let now = dayjs();
let days = now.diff(marsPerseverance, 'days');
console.log(`On ${now.format('YYYY-MM-DD')}, ${days} days have passed since Perseverance landed on Mars.`);
import dayjs from 'dayjs'
let now = dayjs();
// ISO Standard
console.log("ISO")
console.log(now.format());
// Time
console.log("\nTime")
console.log(now.format("HH:mm:ss"));
console.log(now.format("h:mm:ss a"));
// Date
console.log("\nDate")
console.log(now.format("dddd, MMMM D YYYY"));
console.log(now.format("YYYY-MM-DD"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment