Flutter에서는 DateTime.now()
를 사용하여 현재 시간을 불러올 수 있는데, 이는 디바이스에 설정된 시간이다. → 불러오는 값을 사용자가 얼마든지 조작할 수 있다는 의미
디바이스에 설정된 시간에 상관없이, 접속 네트워크 서버 시간을 불러올 수 있도록 하기 위해 많이 사용하는 라이브러리가 바로 ntp
이다.
https://pub.dev/packages/ntp
DateTime currentTime = await NTP.now();
위와 같이 사용하면 된다.
ntp
라이브러리 코드를 열어보면 기본 time server는 time.google.com
으로 되어있는데, 이 서버에서 응답이 잘 오지 않을 때가 있다.
하지만, 구글에서는 time server가 3개 더 있으므로, timeout
을 지정하고 응답이 오지 않을 때 다른 주소를 사용해보도록 구현하면 된다.
late DateTime currentTime;
// 4개의 서버
List<String> ntpAddresses = [
'time.google.com',
'time2.google.com',
'time3.google.com',
'time4.google.com',
];
bool success = false; // 불러오기 성공 여부
// 서버마다 순회
for (String address in ntpAddresses) {
try {
currentTime = await NTP.now(
lookUpAddress: address,
timeout: Duration(seconds: 5), // 5초
);
currentTime = currentTime.toUtc().add(Duration(hours: 9)); // 현재 한국 시간
success = true;
break;
} catch (e) {
print("NTP 서버 실패: $address, $e");
}
}
if (!success) {
throw Exception("NTP 서버에서 시간을 가져올 수 없습니다.");
}