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?
DateTime to TImestampThe millisecondsSinceEpoch property of the DateTime class gives us the number of milliseconds since the “Unix epoch” 1970-01-01T00:00:00Z (UTC). This is the timestamp in milliseconds. If you want the timestamp in seconds, just divide the result by 1000.
Convert it to 24 hours format If we set alwaysUse24HourFormat to true, it might convert to 24 hours format but we need to clone the default setting and then change the value in somewhere.
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);
@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:
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:
More info on Flutter's parse method here - https://api.flutter.dev/flutter/dart-core/DateTime/parse.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With