[Angular -pipe] transferSnsTime
transferSnsTime
Date 형식을 몇분, 몇초 처럼 sns에서 자주 사용하는 시간표시 형식으로 변경
- transferSnsTime.pipe.ts
import { Pipe, PipeTransform, NgModule } from '@angular/core';
@Pipe({name: 'transferSnsTime'})
export class TransferSnsTime implements PipeTransform {
transform(time: number): string {
let rtn: string = '';
const now: any = new Date();
const today: any = new Date(time);
console.log('today:', today);
console.log('today.getTime():', today.getTime());
const dateGap = now.getTime() - today.getTime();
console.log('dateGap', dateGap);
if (dateGap === 0) {
return '방금 전' ;
}
const timeGap = new Date(0, 0, 0, 0, 0, 0, now - today);
const diffDay = Math.floor(dateGap / (1000 * 60 * 60 * 24)); // 일수
const diffHour = timeGap.getHours(); // 시간
const diffMin = timeGap.getMinutes(); // 분
const diffSec = timeGap.getSeconds(); // 초
if (diffDay > 0) {
rtn = diffDay + '일 전';
} else if (diffHour > 0) {
rtn = diffHour + '시간 전';
} else if (diffMin > 0) {
rtn = diffMin + '분 ' + diffSec + '초 전';
} else if (diffSec > 0) {
rtn = diffSec + '초 전'
}
return rtn;
}
}
@NgModule({
declarations: [ TransferSnsTime ],
exports: [ TransferSnsTime ],
})
export class TransferSnsTimePipeModule { }
{{ '2024-02-16T02:50:06.328Z' | transferSnsTime}}
- snsformattime.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'timeToSnsFormat'})
export class TimeToSnsFormat implements PipeTransform {
transform(time: Date): string {
const now = new Date();
const today = new Date(time);
/*
const sYear = time.substring(0,4);
const sMonth = time.substring(4,6)-1;
const sDate = time.substring(6,8);
const sHour = time.substring(8,10);
const sMin = time.substring(10,12);
const sSecond = time.substring(12,14);
const sc = 1000;
const today = new Date(sYear,sMonth,sDate,sHour,sMin,sSecond);
const pastSecond = parseInt((now-today)/sc,10);
*/
const dateGap = now.getTime() - today.getTime();
if (dateGap === 0) { return '방금' ; }
const timeGap = new Date(0, 0, 0, 0, 0, 0, dateGap);
const diffDay = Math.floor(dateGap / (1000 * 60 * 60 * 24)); // 일수
const diffHour = timeGap.getHours(); // 시간
const diffMin = timeGap.getMinutes(); // 분
const diffSec = timeGap.getSeconds(); // 초
if (diffDay > 365) {
return '수년 전';
} else if (diffDay > 30) {
return diffDay % 30 + '달 전';
} else if (diffDay > 0) {
return diffDay + '일 전';
} else if (diffHour > 0) {
return diffHour + '시간 전';
} else if (diffMin > 0) {
return diffMin + '분 ' + diffSec + '초 전';
} else if (diffSec >= 0) {
return '방금전';
} else { // 시간 오류로 - 발생하는 경우
return '방금전';
}
}
}