programing

TypeScript에서 날짜/시간 형식 지정

oldcodes 2023. 6. 23. 22:25
반응형

TypeScript에서 날짜/시간 형식 지정

REST API로부터 아래 형식으로 날짜와 시간을 받고 있습니다.

2016-01-17T:08:44:29+0100

이 날짜와 시간 스탬프의 형식을 다음과 같이 지정하고 싶습니다.

17-01-2016 08:44:29

dd/mm/yyyyhh:mm:ss여야 합니다.

TypeScript로 포맷하는 방법은 무엇입니까?

프로젝트에 moment.js.install moment js를 사용할 수 있습니다.

 moment("2016-01-17T:08:44:29+0100").format('MM/DD/YYYY');

자세한 형식 옵션을 보려면 Moment(모멘트)를 선택합니다.형식()

답을 보세요.

다음을 생성할 수 있습니다.new Date("2016-01-17T08:44:29+0100") //removed a colon개체를 추출한 다음 월, 일, 연도, 시간, 분 및 초를 가져옵니다.Date개체를 선택한 다음 문자열을 만듭니다.스니펫 참조:

const date = new Date("2016-01-17T08:44:29+0100"); // had to remove the colon (:) after the T in order to make it work
const day = date.getDate();
const monthIndex = date.getMonth();
const year = date.getFullYear();
const minutes = date.getMinutes();
const hours = date.getHours();
const seconds = date.getSeconds();
const myFormattedDate = day+"-"+(monthIndex+1)+"-"+year+" "+ hours+":"+minutes+":"+seconds;
document.getElementById("dateExample").innerHTML = myFormattedDate
<p id="dateExample"></p>

그것은 가장 우아한 방법은 아니지만 효과가 있습니다.

이것이 도움이 되는지 확인합니다.

var reTime = /(\d+\-\d+\-\d+)\D\:(\d+\:\d+\:\d+).+/;
var originalTime = '2016-01-17T:08:44:29+0100';
var newTime = originalTime.replace(this.reTime, '$1 $2');
console.log('newTime:', newTime);

출력:

newTime: 2016-01-17 08:44:29

새 날짜().toLocalString()

output:

"31/03/2020 ,00:00:0"

(이제 출력은 문자열입니다.)

언급URL : https://stackoverflow.com/questions/41659206/format-datetime-in-typescript

반응형