1. ホーム
  2. dart

[解決済み] タイムスタンプの変換

2022-09-02 21:26:53

質問

firebaseからデータを取得しているのですが、フィールドの1つがタイムスタンプで、以下のようなものです -> 1522129071. どのように日付に変換するのでしょうか?

Swiftの例(動作します):

func readTimestamp(timestamp: Int) {
    let now = Date()
    let dateFormatter = DateFormatter()
    let date = Date(timeIntervalSince1970: Double(timestamp))
    let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth])
    let diff = Calendar.current.dateComponents(components, from: date, to: now)
    var timeText = ""

    dateFormatter.locale = .current
    dateFormatter.dateFormat = "HH:mm a"

    if diff.second! <= 0 || diff.second! > 0 && diff.minute! == 0 || diff.minute! > 0 && diff.hour! == 0 || diff.hour! > 0 && diff.day! == 0 {
        timeText = dateFormatter.string(from: date)
    }
    if diff.day! > 0 && diff.weekOfMonth! == 0 {
        timeText = (diff.day == 1) ? "\(diff.day!) DAY AGO" : "\(diff.day!) DAYS AGO"
    }
    if diff.weekOfMonth! > 0 {
        timeText = (diff.weekOfMonth == 1) ? "\(diff.weekOfMonth!) WEEK AGO" : "\(diff.weekOfMonth!) WEEKS AGO"
    }

    return timeText
}

Dartでの私の試み。

String readTimestamp(int timestamp) {
    var now = new DateTime.now();
    var format = new DateFormat('HH:mm a');
    var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp);
    var diff = date.difference(now);
    var time = '';

    if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
      time = format.format(date); // Doesn't get called when it should be
    } else {
      time = diff.inDays.toString() + 'DAYS AGO'; // Gets call and it's wrong date
    }

    return time;
}

そして、日付や時刻がめちゃくちゃずれて返ってきます。

UPDATEです。

String readTimestamp(int timestamp) {
    var now = new DateTime.now();
    var format = new DateFormat('HH:mm a');
    var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000);
    var diff = date.difference(now);
    var time = '';

    if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
      time = format.format(date);
    } else {
      if (diff.inDays == 1) {
        time = diff.inDays.toString() + 'DAY AGO';
      } else {
        time = diff.inDays.toString() + 'DAYS AGO';
      }
    }

    return time;
  }

どのように解決するのですか?

タイムスタンプの形式が、マイクロ秒ではなく、秒(Unix タイムスタンプ)になっています。もしそうなら、答えは次のようになります。

変更します。

var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp);

から

var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);