// Define the start and end times // These can now be "h:mm AM/PM" or "HH:mm" String startTimeStr = "8:31 AM"; String endTimeStr = "5:00 PM"; // Example for 24-hour format: // String startTimeStr = "08:46"; // String endTimeStr = "17:30"; // Example for mixed formats: // String startTimeStr = "8:46 AM"; // String endTimeStr = "17:30"; /// Parses a time string, supporting both "h:mm AM/PM" (12-hour) /// and "HH:mm" (24-hour) formats. /// /// Returns a [DateTime] object with a fixed arbitrary date (Jan 1, 2025) /// and the parsed time, or `null` if the string cannot be parsed. DateTime? parseTime(String timeStr) { try { final timeStrUpper = timeStr.toUpperCase(); final is12HourFormat = timeStrUpper.contains("AM") || timeStrUpper.contains("PM"); int hour; int minute; if (is12HourFormat) { final parts = timeStr.split(" "); if (parts.length != 2) return null; // Expected "time meridian" final hmParts = parts[0].split(":"); if (hmParts.length != 2) return null; // Expected "h:mm" hour = int.parse(hmParts[0]); minute = int.parse(hmParts[1]); String meridian = parts[1].toUpperCase(); if (meridian == "PM" && hour != 12) { hour += 12; } else if (meridian == "AM" && hour == 12) { hour = 0; // 12 AM (midnight) is 00:xx in 24-hour format } // Basic validation for parsed hour/minute values if (hour < 0 || hour > 23 || minute < 0 || minute > 59) { return null; } } else { // Assume 24-hour format (HH:mm) final hmParts = timeStr.split(":"); if (hmParts.length != 2) return null; // Expected "HH:mm" hour = int.parse(hmParts[0]); minute = int.parse(hmParts[1]); // Basic validation for parsed hour/minute values if (hour < 0 || hour > 23 || minute < 0 || minute > 59) { return null; } } // Use a fixed date; only the time component is relevant for duration. return DateTime(2025, 1, 1, hour, minute); } on FormatException { // Catch errors from int.parse if the number format is invalid return null; } catch (e) { // Catch any other unexpected errors during parsing return null; } } void main() { DateTime? startTime = parseTime(startTimeStr); DateTime? endTime = parseTime(endTimeStr); if (startTime == null) { print( "Error: Could not parse start time '$startTimeStr'. Please use 'h:mm AM/PM' or 'HH:mm' format.", ); return; } if (endTime == null) { print( "Error: Could not parse end time '$endTimeStr'. Please use 'h:mm AM/PM' or 'HH:mm' format.", ); return; } // Calculate difference Duration difference = endTime.difference(startTime); final int totalMinutes = difference.inMinutes; final int totalHours = difference.inHours; final int minuteAfterHours = totalMinutes - totalHours * 60; print( "The number of minutes from $startTimeStr to $endTimeStr is $totalMinutes minutes / $totalHours hours and $minuteAfterHours minutes.", ); if (totalMinutes < 480) { print('!!!!!!Total minutes does not meet worktime!!!!!!'); } else { print( 'You reached minimum work time, with ${totalMinutes - 480} minutes extra', ); } }