skip to Main Content

I can format the time in my desired format "3:38 PM" but it’s a string type. But I want my to DateTime for later calculations. I can’t manage to parse them. I want to remove this "1970-01-01" from the datetime 1970-01-01 03:38:00.000

I want this string to "3:38 PM" -> this DateTime "03:38:00.000". How can I do that?

import 'package:intl/intl.dart';

void main() {
  String timeStr = "3:38 PM";
  try {
    DateTime parsedTime = DateFormat("HH:mm a").parse(timeStr);

    print(parsedTime); // 1970-01-01 15:38:00.000

    String formattedTime = DateFormat("h:mm a").format(parsedTime);

    print(formattedTime); // Output: 3:38 PM
  } catch (e) {
    print("Invalid time format");
  }
}

2

Answers


  1. You can’t create a DateTime object without the date part. If you don’t pass the date part and tries to parse the string to DateTime, Dart automatically adds epoch date (1970-01-01) to the object.

    Two possible work arounds are:

    1. Handle your logic with today’s Date, and ignore the date part if you’re not using it.
    import 'package:intl/intl.dart';
    
    void main() {
      String timeStr = "3:38 PM";
      try {
        final now = DateTime.now();
        DateTime parsedTime = DateFormat("HH:mm a").parse(timeStr);
    
        DateTime parsedTimeOfToday = DateTime(
          now.year,
          now.month,
          now.day,
          parsedTime.hour,
          parsedTime.minute,
          parsedTime.second,
          parsedTime.millisecond,
          parsedTime.microsecond,
        );
    
        print(parsedTimeOfToday); // 1970-01-01 15:38:00.000
    
        String formattedTime = DateFormat("h:mm a").format(parsedTimeOfToday);
    
        print(formattedTime); // Output: 3:38 PM
      } catch (e) {
        print("Invalid time format");
      }
    }
    
    1. If you just want to handle with Time, then it’s better to create your own Time class and implement the necessary methods on it. Which might in turn simplify computations for yourself.

    Hope this helps 🙂

    Login or Signup to reply.
  2. As said in the class you’re using, it’s a DateTime, so it’s using a date alongside the time of the day, which defaults to 1970-01-01. If you only need hours and minutes (so no seconds, milliseconds…), you could be using TimeOfDay class:

    TimeOfDay.fromDateTime(DateFormat("HH:mm a").parse(timeStr));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search