티스토리 뷰

728x90

Dart에서 현재 시간, 날짜를 DateTime 객체로 가져올 수 있습니다.

 

다양한 예제와 함께 알아보겠습니다.

 

현재 시간의 DateTime 객체

DateTime.now()는 현재 시간, 날짜에 대한 DateTime 객체를 생성하여 리턴합니다.

import 'dart:core';

void main() {
  DateTime now = DateTime.now();
  print("현재 시간: $now");
}

// 현재 시간: 2023-03-08 05:56:13.774260

 

UTC 시간 가져오기

UTC(Epoch) 시간은 1970년 1월 1일에서 현재까지의 시간을 milliseconds로 표현한 것입니다. 1970년 1월 1일은 0 millisecond가 됩니다.

 

DateTime.millisecondsSinceEpoch는 UTC 시간을 가져옵니다.

import 'dart:core';

void main() {
  int milliseconds = DateTime.now().millisecondsSinceEpoch;
  DateTime time = DateTime.fromMillisecondsSinceEpoch(milliseconds);
  print("Epoch Time: $milliseconds");
  print("Time: $time");
}

// Epoch Time: 1678222909446
// Time: 2023-03-08 06:01:49.446

 

다른 날짜 형식으로 시간 가져오기

DateFormat을 이용하면 아래 예제와 같이 DateTime 객체를 원하는 형식의 날짜로 변환할 수 있습니다.

  • yyyy : 년도
  • MM : 월
  • dd : 일
  • kk / mm / ss : 시, 분, 초
import 'dart:core';
import 'package:intl/intl.dart';

void main() {
  DateTime now = DateTime.now();
  String formattedTime = DateFormat('yyyy년 MM월 dd일, kk시 mm분 ss초').format(now);
  print("현재 시간: $formattedTime");
}

// 현재 시간: 2023년 03월 08일, 06시 03분 29초

 

728x90