Reputation: 1877
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.
And i want to display on application in this format
Can you please help me regarding the easiest way of doing the formatting from 24 hr to 12 hr?
Upvotes: 17
Views: 45523
Reputation: 51
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.
Upvotes: 1
Reputation: 51
DateTime now = DateTime.now();
String formattedDate = DateFormat().add_yMMMEd().add_jms().format(now);
O/p:Thu,jul 14,2022 4:50:24 PM
Upvotes: 5
Reputation: 21551
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
Upvotes: 8
Reputation: 11
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;
}
Upvotes: 1
Reputation: 21
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
Upvotes: 2
Reputation: 34220
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
Upvotes: 4
Reputation: 106
You can simply use TimeOfDay class:
var time = TimeOfDay.fromDateTime(DateTime.now());
print(time.hourOfPeriod);
print(time.minute);
print(time.period);
Upvotes: 6
Reputation: 41
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;
}
Upvotes: 4
Reputation: 71
Use Function from import 'package:intl/intl.dart';
library.
DateFormat.Hm().format(date);
it will give a 24 hours format time 23:30
Upvotes: 6
Reputation: 3003
@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),),
)
)
));
}
}
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),),
)
)
));
}
}
More info on Flutter's parse method here - https://api.flutter.dev/flutter/dart-core/DateTime/parse.html
Upvotes: 19
Reputation: 3232
Dart intl
framework helps you to format date/time into any type you want.
Especially for your case, you can use this code.
DateFormat("h:mma").format(date);
Upvotes: 20
Reputation: 1161
You need to import import 'package:intl/intl.dart';
at the top of your file. Then DateFormat("h:mma")
should do the trick.
Upvotes: 5