Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

Write a Dart function to parse this type of string '2023-10-19' to DateTime

  1. User

    Write a Dart function to parse this type of string '2023-10-19' to DateTime

  2. Assistant

    You can use the DateTime.parse() method in Dart to parse the given string into a DateTime object. Here's a Dart function that takes a string in the format 'yyyy-MM-dd' and returns a DateTime object:

    DateTime parseStringToDate(String dateString) {
      try {
        return DateTime.parse(dateString);
      } catch (e) {
        print('Error parsing string to DateTime: $e');
        return null;
      }
    }
    

    You can use this function like this:

    void main() {
      String dateString = '2023-10-19';
      DateTime date = parseStringToDate(dateString);
    
      if (date != null) {
        print('Parsed DateTime: $date');
      } else {
        print('Error parsing string to DateTime');
      }
    }
    

    Output:

    Parsed DateTime: 2023-10-19 00:00:00.000