Reputation: 63
I am getting timestamp from the backend and i wants to display the time the in this format
7:55 PM PKT
it should display the time and the user current country abbreviation how i can achieve in this in flutter
Upvotes: -1
Views: 43
Reputation: 76
First, add the required packages to pubspec.yaml:
intl: ^0.17.0
flutter_native_timezone: ^2.0.0
for the question you asked, the Flutter code would look like this:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: TimeDisplay(
timestamp: DateTime.now().millisecondsSinceEpoch ~/ 1000,
),
);
}
}
class TimeDisplay extends StatefulWidget {
final int timestamp;
TimeDisplay({required this.timestamp});
@override
_TimeDisplayState createState() => _TimeDisplayState();
}
class _TimeDisplayState extends State<TimeDisplay> {
String _formattedTime = '';
String _timezoneAbbreviation = '';
@override
void initState() {
super.initState();
_getTimeZoneAndFormat();
}
Future<void> _getTimeZoneAndFormat() async {
try {
String timeZone = await FlutterNativeTimezone.getLocalTimezone();
DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(widget.timestamp * 1000, isUtc: true);
DateTime localDateTime = dateTime.toLocal();
String formattedTime = DateFormat('h:mm a').format(localDateTime);
String timezoneAbbreviation = _getTimezoneAbbreviation(timeZone);
setState(() {
_formattedTime = formattedTime;
_timezoneAbbreviation = timezoneAbbreviation;
});
} catch (e) {
setState(() {
_formattedTime = 'Error';
_timezoneAbbreviation = '';
});
}
}
String _getTimezoneAbbreviation(String timezone) {
if (timezone == 'Asia/Karachi') {
return 'PKT';
}
return timezone.split('/').last;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Time Display'),
),
body: Center(
child: _formattedTime.isEmpty
? CircularProgressIndicator()
: Text(
'$_formattedTime $_timezoneAbbreviation',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
),
);
}
}
Just note that in this code I get the user's timezone in the _getTimeZoneAndFormat
method, using FlutterNativeTimezone.getLocalTimezone()
If I may suggest, get this from the backend.
And in this method:
String _getTimezoneAbbreviation(String timezone) {
if (timezone == 'Asia/Karachi') {
return 'PKT'; // پاکستان (PKT)
}
///add other timezones here...
return timezone.split('/').last;
}
You can add the time zones you want.
Upvotes: 0