Times With DateFormat
Part of the Data and the Network section of Coddy's Flutter journey. Lesson 21 of 27.
The same DateTime holds the time too, and DateFormat formats it with its own letters:
final start = DateTime.parse('2026-11-03T18:30:00');
DateFormat('h:mm a').format(start) // 6:30 PM
DateFormat('HH:mm').format(start) // 18:30h is the hour on a 12 hour clock and H on a 24 hour clock, mm the minutes, and a adds AM or PM. Two letters keep a leading zero: HH writes 9 o'clock as 09.
Watch the capitals again. Small mm is minutes and capital MM is the month: h:MM a turns 6:30 PM in November into 6:11 PM, because November is month 11.
Challenge
EasyShow when each event starts: give every ListTile a trailing text with the time, so the first event reads 6:30 PM.
Try it yourself
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'api.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: EventsScreen(),
);
}
}
class EventsScreen extends StatefulWidget {
const EventsScreen({super.key});
@override
State<EventsScreen> createState() => _EventsScreenState();
}
class _EventsScreenState extends State<EventsScreen> {
late Future<List<Event>> _events;
@override
void initState() {
super.initState();
_events = loadEvents();
}
Future<List<Event>> loadEvents() async {
final body = await fetch('/events');
final items = jsonDecode(body) as List<dynamic>;
return items.map((item) => Event.fromJson(item as Map<String, dynamic>)).toList();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Events')),
body: FutureBuilder<List<Event>>(
future: _events,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Could not load: ${snapshot.error}'));
}
if (snapshot.hasData) {
final events = snapshot.data!;
return ListView.builder(
itemCount: events.length,
itemBuilder: (context, index) {
final event = events[index];
return ListTile(
title: Text(event.title),
subtitle: Text(DateFormat('EEE, MMM d').format(event.start)),
);
},
);
}
return const Center(child: CircularProgressIndicator());
},
),
);
}
}
class Event {
Event({required this.title, required this.start});
final String title;
final DateTime start;
factory Event.fromJson(Map<String, dynamic> json) {
return Event(
title: json['title'] as String,
start: DateTime.parse(json['start'] as String),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and the Network
Practice on your own: Online Flutter compiler