Thejani Saranaguptha
Thejani Saranaguptha

Reputation: 135

DateFormat in flutter

How to get the hour, minute and am/pm seperately using the bellow format in flutter?

The below is the piece of code i tried,

DateTime now = DateTime.now();
var formatTime = DateFormat("hh:mm a").format(now);

Upvotes: 1

Views: 104

Answers (1)

Santo Shakil
Santo Shakil

Reputation: 1052

import 'package:intl/intl.dart';

void main(List<String> arguments) {
  var now = DateTime.now();
  var formatTime = DateFormat('hh:mm a').format(now);

  //you can get hour minute directly
  var hhDirect = now.hour;
  var mmDirect = now.minute;

  //or your can get with this method
  var splitTimeAndAmPm = formatTime.split(' ');
  var splitHHandMM = splitTimeAndAmPm.first.split(':');

  var am_pm = splitTimeAndAmPm.last;
  var hh = splitHHandMM.first;
  var mm = splitHHandMM.last;

  print('HH Direct: ' + hhDirect.toString());
  print('MM Direct: ' + mmDirect.toString());
  print('HH: ' + hh);
  print('MM: ' + mm);
  print('AmPm: ' + am_pm);
}

Upvotes: 1

Related Questions