skip to Main Content

I stored the date in database as String and call it via model String? myDate;, the data save as 31/12/2023 00:00:00.
I want to dispaly in Text widget as 31/12/2023 not 31/12/2023 00:00:00 so I tried to covnert String to DateTime then to String again but the resutl is 2023-12-31 00:00:00.000

var date = '31/12/2023 00:00:00';
DateTime parseDate = intl.DateFormat("dd/MM/yyyy").parse(date);
var inputDate = DateTime.parse(parseDate.toString());
print(inputDate);
//output: 2023-12-31 00:00:00.000

How to achive my goal?

3

Answers


  1. To achieve your goal you can do following thing

    var date = '31/12/2023 00:00:00';
    DateTime parseDate = DateTime.parse(date);
    var formattedDate = DateFormat("dd/MM/yyyy").format(parseDate);
    print(formattedDate); // Output: 31/12/2023
    

    OR

    you can do everything in one step

    var date = '31/12/2023 00:00:00';
    String formattedDate = DateFormat("dd/MM/yyyy").format(DateTime.parse(date));
    print(formattedDate); // Output: 31/12/2023
    
    Login or Signup to reply.
  2. Just call these methods on the DateTime, its self-explanatory:

    void main() {
      var date = '31/12/2023 00:00:00';
      DateTime parseDate = intl.DateFormat("dd/MM/yyyy").parse(date);
      
      final formattedDate = "${parseDate.day}/${parseDate.month}/${parseDate.year}";
      print(formattedDate);
    }
    

    Prints:

    31/12/2023
    
    Login or Signup to reply.
  3. You need to play around your String and convert it to format that intl.DateFormat can use it.

    This code solves my problem:

    var date = '31/12/2023 00:00:00';
    String dateWithT = "${date.substring(6, 10)}-${date.substring(3, 5)}-${date.substring(0, 2)}T00:00:00.000000Z";
    DateTime parseDate = intl.DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(dateWithT);
    var inputDate = DateTime.parse(parseDate.toString());
    var outputFormat = intl.DateFormat('dd/MM/yyyy');
    var outputDate = outputFormat.format(inputDate);
    print(outputDate);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search