-4

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.

shanmkha
  • 416
  • 1
  • 8
  • 27
  • Are you inputting only 13:00 as string or picking time from a picker? – Kaushik Chandru Oct 23 '21 at 21:38
  • It’s a string [can you go through this link](https://stackoverflow.com/questions/69689003/how-to-get-values-from-one-class-screen-to-another-class-and-populate-those-valu/69689225#69689225) here is my flutter program where Iam selecting 24hrs format time as string(I used 24hrs format because design demands) , but I want to convert it to 12hrs format. Thanks in Advance. – shanmkha Oct 23 '21 at 22:08

3 Answers3

1

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;
}

 
Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
1

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);
0
input 24hrs--0:30
output 12hrs--12:30 am

Code

main(){
  String t = "0:30";
  print("input 24hrs--$t");
  String c = (twelveHourVal(t));
  print("output 12hrs--$c");
}

String twelveHourVal(String inputString)
{
  var splitTime = inputString.split(":");
  int hour = int.parse(splitTime[0]);
  String suffix = "am";
  if(hour > 12)
  {
    hour -= 12;
    suffix = "pm";
   }
   else if(hour == 0)
   {
     hour =12;
     suffix = "am";
   }
   else if(hour == 12)
   {
     hour = 12;
     suffix = "pm";
   }
  
   String twelveHourVal = '$hour:${splitTime[1]} $suffix';
   return twelveHourVal;
 }
Andrew
  • 2,046
  • 1
  • 24
  • 37
shanmkha
  • 416
  • 1
  • 8
  • 27
  • Hey @Andrew , I had posted another question related to flutter camera can you please help me, [here is the link](https://stackoverflow.com/questions/70412440/flutter-image-is-not-capturing-ontap-button-unless-doing-hot-reload?noredirect=1#comment124469642_70412440) – shanmkha Dec 21 '21 at 05:23