Search code examples
datetimeflutterdarttwitter

Trying to convert timestamp from twitter api into DateTime in flutter


To make it more understandable: From Twitter API you will get String Date in this format (Thu Mar 26 11:51:30 +0000 2020) All i want to do is make this String parse with DateTime format so i need to change the format from this (Thu Mar 26 11:51:30 +0000 2020) to something like this (26.04.2020 11:51:30), is this somehow possible ? Thank you :)


Solution

  • You can use substring method of string and cut each and every part then pass all that in datetime.

    I hope Following code solve your issue.

      int month;
      String datetime = "Thu Mar 26 11:51:30 +0000 2020";
      String monthInString = datetime.substring(4, 7);
      int day = int.parse(datetime.substring(8, 10));
      int hours = int.parse(datetime.substring(11, 13));
      int min = int.parse(datetime.substring(14, 16));
      int second = int.parse(datetime.substring(17, 19));
      int year = int.parse(datetime.substring(26, 30));
      DateTime _dateTime;
      switch (monthInString) {
        // add all months
        case 'Jan':
          month = 1;
          break;
        case 'Mar':
          month = 3;
          break;
      }
      _dateTime = DateTime.utc(year, month, day, hours, min, second);
      print(_dateTime);