Home > Back-end >  How to convert 24 hrs (13:00) to 12hrs (1:00 PM) in dart language/Flutter?
How to convert 24 hrs (13:00) to 12hrs (1:00 PM) in dart language/Flutter?

Time:10-24

So I’m trying to convert 24hrs format into 12hrs format time like, my input is 13:00 and output should be 1:00 PM and I didn’t find correct library to do it so could anyone help me.Thanks in Advance.

CodePudding user response:

First split the string

var splitTime = inputString.split(":");

Then convert the first value to an int

int hour = int.parse(splitTime[0]);

Check if the hour is greater than 12

String suffix = "am";
if(hour >= 12)
{
hour -= 12;
suffix = "pm";
}

To summarise use this method

String twelveHourVal(String inputString)
{
var splitTime = inputString.split(":");
int hour = int.parse(splitTime[0]);
String suffix = "am";
if(hour >= 12)
{
  hour -= 12;
  suffix = "pm";
 }
String twelveHourVal = '$hour:${splitTime[1]} $suffix';
 return twelveHourVal;
}

 

CodePudding user response:

Dart intl framework helps you to format date and time into a type you want.

https://pub.dev/packages/intl

example:

DateFormat("h:mma").format(date);
  • Related