반응형

플러터에서 로컬 타임을 불러오는 방법에 대해서 알아보겠다.

 

var now = new DateTime.now(); 

이 코드를 이용하면 시간을 받아올 수 있다, (now는 DateTime 변수이지만, print를 이용해 출력할때는 String처럼 활용이 가능하다)

 

2021-08-31 22:15:43.202188 하지만 다음과 같이, 상당히 보기 어려운 방식으로 출력이 된다.

따라서 이것을 그럴듯하게 출력하는 방법을 알아보겠다. 

우선 pubspec.yaml 파일에 intl을 추가한뒤, (들여쓰기 유의)

1
2
3
4
5
dependencies:
  flutter:
    sdk: flutter
  //원래 있던 것들
  intl: ^0.17.0 //추가한다.
cs

intl을 import해준다.

import 'package:intl/intl.dart'

 

그 뒤 시간을 확인하는 함수를 만들어준다. (사용하기 위해서는 버튼을 사용하고 onPressed에 이 함수를 넣으면 된다)

1
2
3
4
5
6
7
8
9
10
void check_time(BuildContext context){ //context는 Snackbar용, 다른 방식으로 출력할거면 필요없음.
  var now = new DateTime.now(); //반드시 다른 함수에서 해야함, Mypage같은 클래스에서는 사용 불가능
  String formatDate = DateFormat('yy/MM/dd - HH:mm:ss').format(now); //format변경
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar( //출력용 snackbar
      content: Text('$formatDate'),
      duration: Duration(seconds: 20),
    )
  );
}
cs

String formatDate = DateFormat('yy/MM/dd - HH:mm:ss').format(now);  이게 핵심이다. 

여기서 DateFormat의 사용법을 구체적으로 궁금해 하실 것 같은데, 

https://api.flutter.dev/flutter/intl/DateFormat-class.html

 

DateFormat class - intl library - Dart API

DateFormat is for formatting and parsing dates in a locale-sensitive manner. It allows the user to choose from a set of standard date time formats as well as specify a customized pattern under certain locales. Date elements that vary across locales include

api.flutter.dev

다음 링크에서 자세히 알아볼 수 있지만, 많이 사용하는 것만 설명해보겠다. (/ - : 등 특수기호는 알아서 사용하면 됨)

2021년 8월 31일 22시 15분 43초 기준으로 설명함

yy 21 (년도) dd 31 (일)
yyyy 2021 (년도) EEEE Tuesday (요일)
MM 08 (월) E Tue (요일)
MMM Aug (월) mm 15 (분)
MMMM August (월) ss 43 (초)

(MM, dd, HH, ss, mm를 한자리로만 쓸경우, 앞에 0이 붙지않음 (08->8)) 

 

 

반응형

'Flutter' 카테고리의 다른 글

flutter alligment 사용법  (0) 2021.09.05
Flutter 기본 코드(심화편)  (0) 2021.09.03
Flutter firestore database 존재성, 데이터 가져오기  (0) 2021.08.30
Flutter Firestore database 사용법  (0) 2021.08.28
Flutter TextField 사용법  (0) 2021.08.26

+ Recent posts