How to format time in Dart?

Viewed 2757

I tried to build an application which should give out the local time from Vienna. I formatted the time with time = DateFormat.jm().format(), but now I get a time like 14:25 PM. How can I delete the PM, because I don´t need it? This is the code I tried:

class _MyHomePageState extends State<MyHomePage> {
  void getTime() async {
    String time;

    Response response =
        await get("http://worldtimeapi.org/api/timezone/Europe/Vienna");
    Map data = jsonDecode(response.body);

    String datetime = data["datetime"];
    String offset = data["utc_offset"].substring(1, 3);
    DateTime now = DateTime.parse(datetime);
    now = now.add(Duration(hours: int.parse(offset)));
    time = DateFormat.jm().format(now);
    print(time);
  }

And this is the time I get:

I/flutter ( 9302): 12:43 PM
3 Answers

If you are using the Intl package then you can do that without too much work by simply provide a custom formatter.

For your use-case you need to use the formatter HH:mm wich represents hour and minutes only.

final date = DateTime.now();
final hourAndMinues = DateFormat('HH:mm').format(date);

print(hourAndMinutes); // 12:00

If you want to show DateTime object in local time in h:m format than you can do following

var local = dateTime.toLocal();
var format = DateFormat("HH:mm").format(local); //or h:m for 12 hour format without am/pm
print(format);

Just Replace

This line

time = DateFormat.jm().format(now);

With

time = DateFormat.Hm().format(now);   // Hm Indicate hour and minute
Related