DateTime

shin·2023년 1월 19일
0

Dart

목록 보기
19/20

DateTime

  • 날짜와 관련될 때 DateTime을 사용한다.
  • 현재시간과 날짜를 출력할 때는 now()를 사용한다.
void main() {
  DateTime now = DateTime.now();
  print(now);
}

결과는 현재 날짜와 시간이 출력된다.
2023-01-01 17:24:02.665

  • getter를 사용해서 각 날짜와 시간만 출력할 수 있다.
  print(now.year);
  print(now.month);
  print(now.day);
  print(now.hour);
  print(now.minute);
  print(now.second);
  print(now.millisecond);




특정한 날짜

  • 특정할 날짜를 불러올 때는 DateTime 생성자를 그냥 실행하면 된다.
  • 생성자 안에는 positional 파라미터를 넣을 수 있다.
  • 순서는 위에 날짜를 출력했던 순서대로 넣어주면 되고 년도만 필수적으로 넣어주고 나머지는 optional로 넣어주면 된다.
void main() {
  
  DateTime specificDay = DateTime(
    2022,
    01,
    19
  );
  
  print(specificDay);
  
}
결과는 
2022-01-19 00:00:00.000




Duration

  • Duration은 기간을 나타낼 때 사용한다.
  • 기간을 60초로 설정하고 출력하면
void main() {
  
  Duration duration = Duration(seconds: 60);
  
  print(duration);
  print(duration.inDays);
  print(duration.inHours);
  print(duration.inMinutes);
  print(duration.inSeconds);
  print(duration.inMilliseconds);
  
}
 결과는 
0:01:00.000000
0 
0
1
60
60000




여러 사용법



difference

  • difference를 사용해서 기간을 구할 수 있다.
void main() {
  DateTime now = DateTime.now();

  DateTime specificDay = DateTime(
    2017,
    11,
    23,
  );
  print(specificDay);
  // 특정 날짜에서 지정한 기간까지의 시간 구하기
  final difference = now.difference(specificDay);

  print(difference);
  print(difference.inDays);
  print(difference.inHours);
  print(difference.inMinutes);

}

결과값
45210:11:51.592000
1883
45210
2712611

이전 이후

  • isAfter : 현재날짜가 특정날짜 이후인지
  • isBefore : 현재날짜가 특정날짜 이전인지
void main() {
  DateTime now = DateTime.now();

  DateTime specificDay = DateTime(
    2017,
    11,
    23,
  );
  

  // 현재날짜가 특정날짜 이후인지
  print(now.isAfter(specificDay));
  // 현재날짜가 특정날짜 이전인지
  print(now.isBefore(specificDay));

}

결과값
true
false
  • 현재날짜를 2020.01.01이라고 가정한다면 isAfter는 true,
    isBefore는 false를 반환한다.

더하기 빼기

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

  // 현재날짜에 시간 더하기, 빼기
  print(now.add(Duration(hours: 10)));
  print(now.subtract(Duration(seconds: 20)));
}

0개의 댓글