모든 시간 두자리로 만들기
////////// 현재 시간 반환 함수(모든 수 두자리)
const currentTime = () => {
// 현재 시각을 나타내는 JavaScript Date 객체 생성
const t = new Date();
// 년, 월, 일, 시, 분, 초 추출
const year = t.getFullYear();
const month = String(t.getMonth() + 1).padStart(2, "0"); // 월은 0부터 시작하므로 1을 더하고, padStart로 두 자리로 만듭니다.
const day = String(t.getDate()).padStart(2, "0"); // 일도 padStart로 두 자리로 만듭니다.
const hours = String(t.getHours()).padStart(2, "0"); // 시도 padStart로 두 자리로 만듭니다.
const minutes = String(t.getMinutes()).padStart(2, "0"); // 분도 padStart로 두 자리로 만듭니다.
const seconds = String(t.getSeconds()).padStart(2, "0"); // 초도 padStart로 두 자리로 만듭니다.
const returnTime = `${year}년${month}월${day}일${hours}시${minutes}분${seconds}초`;
return returnTime;
};
원하는 시간 추출하기
// 시간을 추출할 문자열
const time = "2024년01월23일12시27분";
const extractionTime = (str, startChar, endChar) => {
////////// 게시글 시간
const startIndex = articleInfo.time.indexOf(startChar) + 1; //startChar문자 다음부터
const endIndex = articleInfo.time.indexOf(endChar) + 1; // endChar 문자까지
//startChar문자 다음부터 endChar 문자까 사이의 문자열
const returnStr = articleInfo.time.substring(startIndex, endIndex);
console.log("추출된 문자열 >>", returnStr);
}
extractionTime(time, "년", "일"); //"01월23일"이 콘솔에 찍힌다.