Menu
CoddyTech

Horas con DateFormat

Parte de la sección Datos y red del Journey de Flutter de Coddy. Lección 21 de 27.

El mismo DateTime también contiene la hora, y DateFormat le da formato con sus propias letras:

final start = DateTime.parse('2026-11-03T18:30:00');
DateFormat('h:mm a').format(start)   // 6:30 PM
DateFormat('HH:mm').format(start)    // 18:30

h representa la hora en un reloj de 12 horas y H en uno de 24 horas, mm los minutos, y a añade AM o PM. Dos letras mantienen un cero inicial: HH escribe las 9 en punto como 09.

Fíjate de nuevo en las mayúsculas. La mm minúscula representa los minutos y la MM mayúscula el mes: h:MM a convierte las 6:30 PM de noviembre en 6:11 PM, porque noviembre es el mes 11.

challenge icon

Desafío

Fácil

Muestra cuándo empieza cada evento: añade a cada ListTile un texto trailing con la hora, para que el primer evento indique 6:30 PM.

Pruébalo tú mismo

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),
    );
  }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Datos y red

Practica por tu cuenta: Compilador de Flutter online