-1

I am tring to convert a simple string into a date time but it is showing invalid exception. Here's the code :

void main() {
  String date = '12';
  date = DateTime.parse(date).toString();
  print(date);
}

Can anyone help ?

Arijeet
  • 935
  • 5
  • 19
  • 2
    What kind of date do you expect to get for `12`? Maybe you should try something like `2022-01-13`. – Oliver Jan 13 '22 at 07:07
  • format your date string in `yyyy-mm-dd` to parse it. – Faiizii Awan Jan 13 '22 at 07:08
  • It's unclear what result you expect for your example, but in general, see [How do I convert a date/time string to a DateTime object in Dart?](https://stackoverflow.com/q/49385303/) – jamesdlin Jan 13 '22 at 08:27

2 Answers2

1

Your date string is not valid. Here is example of it:

String time = '2022-01-13';

DateTime parseDate = DateFormat("yyyy-MM-dd").parse(time); // to be date
var inputDate = DateTime.parse(parseDate.toString()); // to be string

var outputFormat = DateFormat('dd MMM yyyy'); // set format be for ex 13 Jan 2022
var outputDate = outputFormat.format(inputDate); // set to be a string
1

While it doesn't make much sense in this form, it will work:

import 'package:intl/intl.dart';

void main() {
  String date = '12';
  DateTime dateTime = DateFormat("MM").parse(date);
  print(dateTime);
}
Oliver
  • 43,366
  • 8
  • 94
  • 151