# Some js methods about date

Posted by roots on Mon, 30 Dec 2019 16:13:14 +0100

Green date format or 2018-08-08 format converted to 20180808 format

```/* Conversion date: 20180808 */
transformData (date) {
let _date = new Date(date)
let m = (_date.getMonth() + 1) < 10 ? '0' + (_date.getMonth() + 1) : (_date.getMonth() + 1)
let d = _date.getDate() < 10 ? '0' + _date.getDate() : _date.getDate()
let _result = _date.getFullYear() + '' + m + '' + d;
return _result
}```

Get the date n days ago and convert to 2018-08-08 format

```/* Get date n days ago */
getDate () {
let myDate = new Date()；
let dateNow = new Date(myDate - 1000 * 60 * 60 * 24 * n);
let nowY = dateNow.getFullYear();
let nowM = dateNow.getMonth() + 1;
let nowD = dateNow.getDate();
let enddate = nowY + '' + (nowM < 10 ? '0' + nowM : nowM) + '' + (nowD < 10 ? '0' + nowD : nowD);
return enddate
}```

Calculate the number of days between two dates (green date or 2018-08-08 date format)

```/* Calculate days between two dates */
daysBetween (date1, date2) {
var bDate = new Date(date2)
var aDay = 24 * 60 * 60 * 1000;
return diffDay
},```

Compare the size of two dates (date format is 2018-01-01 or green date format)

```/* Calculate the size of two dates date1 is greater than date2 return - 1 */
tab (date1, date2) {
var oDate1 = new Date(date1)
var oDate2 = new Date(date2)
if (oDate1.getTime() > oDate2.getTime()) {
return -1
} else {
return 0
}
},```

Get the date of the previous month and the previous 13 months, or the date of the previous day and the previous 31 days

```/* Obtain the dates of the previous month and the previous 13 months or the previous day and the previous 31 days */
getDate (type) {
if (type === 'm') {
let dEnd = new Date()
// Get previous month date
let yEnd = dEnd.getFullYear()
let mEnd = dEnd.getMonth();
mEnd = ((mEnd === 0) ? (12) : (mEnd));
mEnd = mEnd < 10 ? '0' + mEnd : mEnd;
// Date before acquisition 13 months ago
let yStart = dEnd.getFullYear() - 1
return {start: yStart + '-' + mEnd, end: yEnd + '-' + mEnd}
} else if (type === 'd') {
let myDate = new Date();
//  Get one day date
let dateNow = new Date(myDate - 1000 * 60 * 60 * 24 * 1);
let nowY = dateNow.getFullYear();
let nowM = dateNow.getMonth() + 1;
let nowD = dateNow.getDate();
let enddate = nowY + '-' + (nowM < 10 ? '0' + nowM : nowM) + '-' + (nowD < 10 ? '0' + nowD : nowD);
// Get 31 day date
let dateLast = new Date(myDate - 1000 * 60 * 60 * 24 * 30);
let lastY = dateLast.getFullYear();
let lastM = dateLast.getMonth() + 1;
let lastD = dateLast.getDate();
let startdate = lastY + '-' + (lastM < 10 ? '0' + lastM : lastM) + '-' + (lastD < 10 ? '0' + lastD : lastD);
return {start: startdate, end: enddate}
}
},```