📅  最后修改于: 2023-12-03 15:17:41.042000             🧑  作者: Mango
As a developer, we often need to work with dates and times. Moment.js is a popular JavaScript library that makes it easy to work with dates and times in JavaScript. However, if you are working with Shell or Bash scripts, you can also use Moment.js to manipulate dates and times. In this article, we will explore how to use Moment.js in Shell/Bash scripts.
To use Moment.js in your Shell/Bash script, you need to install Moment.js first. You can download the latest version of Moment.js from the official website or use a package manager like npm or yarn. Here is how you can install Moment.js using npm:
npm install moment --save
Once you have installed Moment.js, you can start using it in your Shell/Bash script. Here are some examples of how to use Moment.js:
To get the current date and time, you can use the date
command in Shell/Bash:
now=$(date +"%Y-%m-%d %H:%M:%S")
echo $now
Output:
2021-11-18 20:38:45
Alternatively, you can use Moment.js to get the current date and time:
now=`node -p "require('moment')().format('YYYY-MM-DD HH:mm:ss')"`
echo $now
Output:
2021-11-18 20:38:45
To add or subtract days from a specific date, you can use Moment.js:
date="2021-11-18"
next_day=`node -p "require('moment')('$date').add(1, 'days').format('YYYY-MM-DD')"`
echo $next_day
Output:
2021-11-19
To compare two dates, you can use Moment.js:
date1="2021-11-18"
date2="2021-11-19"
if [ `node -p "require('moment')('$date1').isBefore('$date2')" == "true" ]; then
echo "date1 is before date2"
else
echo "date1 is after date2"
fi
Output:
date1 is before date2
In this article, we have learned how to use Moment.js in Shell/Bash scripts to manipulate dates and times. Moment.js is a powerful and flexible library that makes working with dates and times a lot easier in JavaScript as well as other programming languages.