16

I am working on flutter application where i have to show time stamps but the response i got from api is in 24 hr format and i want to display time in 12 hr format in my application.Here is the json response from api

And i want to display on application in this format I want in this format Can you please help me regarding the easiest way of doing the formatting from 24 hr to 12 hr?

Umair
  • 1,759
  • 6
  • 23
  • 44

12 Answers12

19

Dart intl framework helps you to format date/time into any type you want.

https://pub.dev/packages/intl

Especially for your case, you can use this code.

DateFormat("h:mma").format(date);
Ares
  • 2,504
  • 19
  • 19
18

@Umair, as Sam pointed out, you can use intl package and can use jm() function without explicitly declaring the format like so,

For default DateTime

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text('Test'),
            ),
            body: Padding(
                padding: EdgeInsets.all(20.0),
                child: Center(
                  child: Text(new DateFormat.jm().format(DateTime.now()), style: TextStyle(fontSize: 18.0),),
                )
            )
        ));
  }
}

Screenshot: screenshot

For 24 hr timestamp string

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    String timeStamp24HR = "2020-07-20T18:15:12";

    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text('Test'),
            ),
            body: Padding(
                padding: EdgeInsets.all(20.0),
                child: Center(
                  child: Text(new DateFormat.jm().format(DateTime.parse(timeStamp24HR)), style: TextStyle(fontSize: 18.0),),
                )
            )
        ));
  }
}

Screenshot: 24hr time string

More info on Flutter's parse method here - https://api.flutter.dev/flutter/dart-core/DateTime/parse.html

Pro
  • 2,843
  • 1
  • 18
  • 29
8

To convert UTC time to local time with the specified format including date

Import the below package:

package:intl/intl.dart';

Convert like below:

var dateFormat = DateFormat("dd-MM-yyyy hh:mm aa"); // you can change the format here
var utcDate = dateFormat.format(DateTime.parse(uTCTime)); // pass the UTC time here
var localDate = dateFormat.parse(utcDate, true).toLocal().toString();
String createdDate = dateFormat.format(DateTime.parse(localDate)); // you will get local time
Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138
  • It will be better if you mention the package for using DateFormat class, which is 'import 'package:intl/intl.dart'; ' – devu mani Jun 22 '21 at 13:53
5

You need to import import 'package:intl/intl.dart'; at the top of your file. Then DateFormat("h:mma") should do the trick.

sam
  • 966
  • 6
  • 10
5

Use Function from import 'package:intl/intl.dart'; library.

DateFormat.Hm().format(date);

it will give a 24 hours format time 23:30

BalaDhruv
  • 61
  • 2
  • 4
5

You can simply use TimeOfDay class:

var time = TimeOfDay.fromDateTime(DateTime.now());
print(time.hourOfPeriod);
print(time.minute);
print(time.period);
Rama Alty
  • 96
  • 1
  • 6
5
DateTime now = DateTime.now();
String formattedDate = DateFormat().add_yMMMEd().add_jms().format(now);

O/p:Thu,jul 14,2022 4:50:24 PM

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Hariprasath S
  • 51
  • 1
  • 1
4
  String utcTo12HourFormat(String bigTime) {
    DateTime tempDate = DateFormat("hh:mm").parse(bigTime);
    var dateFormat = DateFormat("h:mm a"); // you can change the format here
    var utcDate = dateFormat.format(tempDate); // pass the UTC time here
    var localDate = dateFormat.parse(utcDate, true).toLocal().toString();
    String createdDate = dateFormat.format(DateTime.parse(localDate));
    print("------------$createdDate");
    return createdDate;
  }
4

The below example shows how to get time from the picker and convert it using DateFormat("h:mm a"), here a denotes AM and PM

TimeOfDay? _selectedTime;

Future<Null> _selectTime(BuildContext context) async {
    final TimeOfDay? timePicked = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );
    if (timePicked != null)
      setState(() {
        _selectedTime = timePicked;
      });
    // Conversion logic starts here
    DateTime tempDate = DateFormat("hh:mm").parse(
        _selectedTime!.hour.toString() +
            ":" + _selectedTime!.minute.toString());
    var dateFormat = DateFormat("h:mm a"); // you can change the format here
    print(dateFormat.format(tempDate));
  }

Output:

flutter: 8:00 PM

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
1

input: 23:43

  var time = "12:00";
  var temp = int.parse(time.split(':')[0]);
  String? t;
  if(temp >= 12 && temp <24){
    t = " PM";
  }
  else{
    t = " AM";
  }
  if (temp > 12) {
    temp = temp - 12;
    if (temp < 10) {
      time = time.replaceRange(0, 2, "0$temp");
      time += t;
    } else {
      time = time.replaceRange(0, 2, "$temp");
      time += t;
    }
  } else if (temp == 00) {
    time = time.replaceRange(0, 2, '12');
    time += t;
  }else{
    time += t;
  }

output: 11:43 PM

1
String time24to12Format(String time) {
int h = int.parse(time.split(":").first);
int m = int.parse(time.split(":").last.split(" ").first);
String send = "";
if (h > 12) {
  var temp = h - 12;
  send =
      "0$temp:${m.toString().length == 1 ? "0" + m.toString() : m.toString()} " +
          "PM";
} else {
  send =
      "$h:${m.toString().length == 1 ? "0" + m.toString() : m.toString()}  " +
          "AM";
}

return send;

}

Jay Gohil
  • 11
  • 1
1

Here are almost all the conversions of Date and time you can use in any Flutter app. This library will help you out in almost each format for date and time both import 'package:intl/intl.dart';

24hr -> 12 hr format:
var to12HrFormate = DateFormat("dd-MM-yyyy hh:mm aa")
    .format(yourDateandTime)  //if your datetime is in DateTime type use this method
       
var to12HrFormat = DateFormat("dd-MM-yyyy hh:mm aa") 
    .format(DateTime.parse(yourDateandTime)); //if your datetime is in String type use this method 

if you only want to convert time only just change the format from DateFormat(dd-MM-yyyy hh:mm aa) to DateFormat(hh:mm aa)

12hr -> 24 hr format:
DateTime to24HrFormat= DateFormat("hh:mm a").parse(yourAMPMTime); // if you want type in DateTime
String to24HrFormat= DateFormat("hh:mm a").format(yourAMPMTime); //if you want the return type in String

here is a little explanation of Type Conversion in time

String -> DateTime:

  static DateTime parseStringDate(String dateString,
  {String format = 'yyyy-MM-d', bool localFromUTc = false}) {
if (dateString.isEmpty) return DateTime.now();
if (dateString.contains('am') || dateString.contains('pm')) {
  dateString =
      dateString.replaceFirst(' pm', ' PM').replaceFirst(' am', ' AM');
}
var date = DateFormat(format).parse(dateasString, localFromUTc).toLocal(); //for DateTime to String conversion use .format(dateasDateTime) in place of .parse()
return date;
 }

Date In Format:

  static String getDateInFormat(DateTime dateTime,
  {String format = 'd/M/yyyy'}) {
return DateFormat(format).format(dateTime);
}

if you only want a single item from date like day, month or year pass dd for day MMMM for month and yyyy in format in above function.