0

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?

isherwood
  • 58,414
  • 16
  • 114
  • 157

2 Answers2

0

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
MendelG
  • 14,885
  • 4
  • 25
  • 52
  • 31-12-2023 not as 31/12/2023 –  Jun 26 '23 at 19:04
  • @Liam this is also solve the problem but change - with / as `final formattedDate = "${parseDate.day}/${parseDate.month}/${parseDate.year}";` I will delete my answer but I hope someone to get another idea from my code. sometimes when you read anything you got another idea so I will keep my answer for others. – Abdullah Bahattab Jun 26 '23 at 19:10
  • @Liam I edited my answer for the desired output. – MendelG Jun 26 '23 at 19:14
  • Yes this answer is better and short but I got a problem when i i have a date 01/07/2023 so this answer make it 1/7/2023 while i need it as 01/07/2023. Thank you for both. @AbdullahBahattab answer for my problem –  Jun 26 '23 at 19:32
-1

You need to play around your String and convert it to format that intl.DateFormat can use it.

This code solves my problem:

try it in dartpad.dev

import 'package:intl/intl.dart' as intl;

void main() {
    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);
}
Abdullah Bahattab
  • 612
  • 1
  • 16
  • 32