Skip to content

Instantly share code, notes, and snippets.

@yankyaw-moe
Created February 1, 2022 14:16
Show Gist options
  • Select an option

  • Save yankyaw-moe/79bb5da8ade95f9a280fdb0906b9964e to your computer and use it in GitHub Desktop.

Select an option

Save yankyaw-moe/79bb5da8ade95f9a280fdb0906b9964e to your computer and use it in GitHub Desktop.
JS Date with native and momentjs
##Moment JS
console.log('current year ', moment().year()); // 2022
console.log('current year ', moment().year(Number)); // Moment<2022-02-01T20:33:23+06:30>
console.log('last year ', moment().subtract(1, 'year').year()); // 2021
console.log('last year ', moment().subtract(1, 'year').year(Number)); // Moment<2021-02-01T20:33:23+06:30>
console.log('current month ', moment().month()); // 1 (20220201)
console.log('last month ', moment().subtract(1, 'month').month()); // 0 (for january)
console.log('current date ', moment().date()); // 1
console.log('current date ', moment().toDate()); // 2022-01-31T10:14:35.618Z
console.log('last date ', moment().subtract(1, 'days').date()); // 31
console.log('last date ', moment().subtract(1, 'days').toISOString()); // 2022-01-30T10:14:35.629Z
let thisYear = moment().format('YYYY'); // 2022
let thisMonth = moment().format('YYYYMM'); // 202202
let today = moment().format('YYYYMMDD'); // 20220201
let lastMonth = moment().subtract(1, 'month').format('YYYYMM'); 202201
let yesterday = moment().subtract(1, 'days').format('YYYYMMDD'); 20220131
let daysOfCurrentMonth = moment().daysInMonth();
let monthDataBSC = new Array(daysOfCurrentMonth).fill(0);
let monthDataETH = new Array(daysOfCurrentMonth).fill(0);
let monthDataMATIC = new Array(daysOfCurrentMonth).fill(0);
let dateString = moment().format('YYYY-MM-DD:HHmmss')
let filename = dateString + '.csv';
##JS Native
let date = new Date();
let thisYear = date.getFullYear();
let lastYear = date.getFullYear() - 1;
// console.log('thisYear ', thisYear)
let thisMonth = date.getMonth();
let lastMonth = date.getMonth() === 0 ? 11 : date.getMonth() - 1;
// console.log('thisMonth ', thisMonth)
let thisDate = date.getDate();
let yesterday = new Date(new Date().getTime() - 24 * 60 * 60 * 1000).getDate();
// console.log('thisDate ', thisDate)
let daysOfCurrentMonth = new Date(thisYear, thisMonth, 0).getDate();
let date = new Date();
let dateString = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ':' + date.getHours() + date.getMinutes() + date.getSeconds();
let filename = dateString + '.csv';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment