Flutter中如何将DateTime列表转换为带AM/PM的时间格式
Convert List to AM/PM Time Format
To convert your List<DateTime> into the desired 12-hour format with AM/PM indicator, you can use Dart's intl package for reliable date/time formatting.
Step 1: Add the intl Dependency
First, include the intl package in your pubspec.yaml:
dependencies: intl: ^0.18.1 # Use the latest version available on pub.dev
Step 2: Format the DateTime List
Use DateFormat with the pattern h:mm a to transform each entry in your list. This pattern gives you 12-hour hour values, two-digit minutes, and the AM/PM marker:
import 'package:intl/intl.dart'; void main() { List<DateTime> listOfDateTime = [ DateTime(2022, 10, 10, 14, 30, 45), DateTime(2022, 10, 10, 17, 30, 45), DateTime(2022, 10, 10, 18, 0, 45), DateTime(2022, 10, 10, 18, 30, 45), DateTime(2022, 10, 10, 19, 30, 45), DateTime(2022, 10, 10, 22, 0, 45), DateTime(2022, 10, 12, 17, 0, 55), DateTime(2022, 10, 14, 17, 0, 55), DateTime(2022, 10, 10, 14, 0, 45), ]; // Initialize the time formatter final timeFormatter = DateFormat('h:mm a'); // Convert each DateTime to the target format List<String> formattedTimes = listOfDateTime.map(timeFormatter.format).toList(); // Print the result print(formattedTimes); }
Pattern Breakdown:
h: 12-hour format (1-12, no leading zero)mm: Two-digit minutes (00-59)a: Uppercase AM/PM indicator
If you want leading zeros for hours (e.g., 02:30 PM instead of 2:30 PM), use the pattern hh:mm a instead.
Expected Output:
[2:30 PM, 5:30 PM, 6:00 PM, 6:30 PM, 7:30 PM, 10:00 PM, 5:00 PM, 5:00 PM, 2:00 PM]
内容的提问来源于stack exchange,提问作者Ashu Upadhyay
相关产品推荐
相关产品推荐

