[flutter] 플러터에서 날짜와 시간을 정해진 형식으로 변환하는 방법

다음은 날짜와 시간을 원하는 형식으로 변환하는 방법을 안내합니다.

필요한 패키지 가져오기

먼저 intl 패키지를 가져와야 합니다. 이를 위해서는 pubspec.yaml 파일에 다음과 같이 추가합니다:

dependencies:
  flutter:
    sdk: flutter
  intl: ^0.17.0

이후 터미널에서 다음 명령어를 실행하여 패키지를 가져옵니다:

$ flutter pub get

날짜와 시간 변환하기

이제 코드에서 intl 패키지를 이용하여 날짜와 시간을 변환할 수 있습니다. 다음은 예제 코드입니다.

import 'package:intl/intl.dart';

void main() {
  var now = DateTime.now();

  var dateFormat = DateFormat('yyyy-MM-dd');
  var timeFormat = DateFormat('HH:mm:ss');

  var formattedDate = dateFormat.format(now);
  var formattedTime = timeFormat.format(now);

  print('Formatted Date: $formattedDate');  // 출력: Formatted Date: 2022-08-15
  print('Formatted Time: $formattedTime');  // 출력: Formatted Time: 13:45:28
}

위 코드에서 DateFormat 클래스를 사용하여 원하는 날짜 및 시간 형식을 설정하고, format 메서드를 호출하여 형식화된 값을 얻을 수 있습니다.

이렇게 하면 플러터에서 날짜와 시간을 손쉽게 원하는 형식으로 변환할 수 있습니다.

더 자세한 내용은 Intl 패키지 문서를 참조해 주세요!