Berbagi teknologi

Sintaks yang biasa digunakan di Moment.js

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Moment.js adalah pustaka pemrosesan tanggal JavaScript yang banyak digunakan yang menyediakan API kaya untuk mengurai, memverifikasi, memanipulasi, dan menampilkan tanggal dan waktu. Berikut ini adalah beberapa contoh sintaks yang umum digunakan di Moment.js:

1. Inisialisasi objek Momen

  1. // 使用当前时间
  2. let now = moment();
  3. // 使用特定的日期时间字符串
  4. let specificDate = moment("2023-04-01T12:00:00");
  5. // 使用 Date 对象
  6. let dateObj = new Date();
  7. let fromDateObj = moment(dateObj);
  8. // 解析非标准格式的日期字符串
  9. let customFormat = moment("01-04-2023", "DD-MM-YYYY");

2. Format tanggal

  1. let formattedDate = moment().format('YYYY-MM-DD HH:mm:ss');
  2. console.log(formattedDate); // 输出类似 "2023-04-01 12:00:00"
  3. // 自定义输出格式
  4. let customFormatted = moment().format('dddd, MMMM Do YYYY, h:mm:ss a');
  5. console.log(customFormatted); // 输出类似 "Saturday, April 1st 2023, 12:00:00 pm"

3. Operasi tanggal

  1. // 添加时间
  2. let futureDate = moment().add(7, 'days');
  3. console.log(futureDate.format('YYYY-MM-DD')); // 输出未来7天的日期
  4. // 减去时间
  5. let pastDate = moment().subtract(1, 'months');
  6. console.log(pastDate.format('YYYY-MM-DD')); // 输出上个月的今天
  7. // 开始和结束时间
  8. let startOfMonth = moment().startOf('month');
  9. let endOfMonth = moment().endOf('month');
  10. console.log(startOfMonth.format('YYYY-MM-DD'));
  11. console.log(endOfMonth.format('YYYY-MM-DD'));

4. Perbandingan tanggal

  1. let date1 = moment("2023-04-01");
  2. let date2 = moment("2023-05-01");
  3. // 是否相等
  4. if (date1.isSame(date2)) {
  5. console.log('Dates are the same');
  6. } else {
  7. console.log('Dates are not the same');
  8. }
  9. // 是否在某个时间之前
  10. if (date1.isBefore(date2)) {
  11. console.log('Date1 is before Date2');
  12. }
  13. // 是否在某个时间之后
  14. if (date2.isAfter(date1)) {
  15. console.log('Date2 is after Date1');
  16. }

5. Perbedaan tanggal

  1. let start = moment("2023-01-01");
  2. let end = moment("2023-04-01");
  3. // 获取两个日期之间的差异(以天为单位)
  4. let diffDays = end.diff(start, 'days');
  5. console.log(diffDays); // 输出 90 或类似值
  6. // 也可以获取月份、年份等差异
  7. let diffMonths = end.diff(start, 'months');
  8. let diffYears = end.diff(start, 'years');
  9. console.log(diffMonths);
  10. console.log(diffYears);

6. Permintaan tanggal

  1. let today = moment();
  2. // 是否是周末
  3. if (today.isWeekend()) {
  4. console.log('Today is a weekend');
  5. }
  6. // 今天是星期几(数字形式,0代表星期天,6代表星期六)
  7. let dayOfWeek = today.day();
  8. console.log(dayOfWeek);
  9. // 今天是几月几号
  10. let month = today.month() + 1; // 注意月份是从0开始的
  11. let date = today.date();
  12. console.log(month + '/' + date);