Flutter开发:如何将指定时区时间转换为目标时区时间?
Hey there! Converting between timezones in Flutter is a common task, and the timezone package (along with intl for date parsing/formatting) makes this straightforward. Let's walk through a step-by-step solution tailored to your needs.
First, you'll need two packages to handle timezone logic and date formatting. Add these to your pubspec.yaml:
dependencies: flutter: sdk: flutter timezone: ^0.9.2 # Use the latest version available intl: ^0.18.1
Run flutter pub get to install them.
The timezone package relies on a timezone database to map IANA timezone IDs to their offsets. Initialize this data in your main() function before running the app:
import 'package:flutter/material.dart'; import 'package:timezone/timezone.dart' as tz; import 'package:timezone/data/latest_all.dart' as tz; import 'package:intl/intl.dart'; void main() async { // Ensure Flutter bindings are ready before async operations WidgetsFlutterBinding.ensureInitialized(); // Load the full timezone database tz.initializeTimeZones(); runApp(const MyApp()); }
Here's a reusable function that takes your source timezone, source time string, and target timezone, then returns the converted time as a readable string:
String convertTimeBetweenZones( String sourceTimeZoneId, String sourceTimeStr, String targetTimeZoneId, ) { try { // 1. Fetch timezone locations for source and target final sourceLocation = tz.getLocation(sourceTimeZoneId); final targetLocation = tz.getLocation(targetTimeZoneId); // 2. Parse the input time string into a timezone-aware DateTime // Adjust the DateFormat pattern to match your input format (e.g., 24h vs 12h) final inputFormatter = DateFormat('yyyy-MM-dd hh:mm a', 'en_US'); final localDateTime = inputFormatter.parse(sourceTimeStr); final sourceTZDateTime = tz.TZDateTime.from(localDateTime, sourceLocation); // 3. Convert directly to the target timezone final targetTZDateTime = tz.TZDateTime.from(sourceTZDateTime, targetLocation); // 4. Format the result into a user-friendly string final outputFormatter = DateFormat('yyyy-MM-dd hh:mm a', 'en_US'); return outputFormatter.format(targetTZDateTime); } catch (e) { // Handle invalid timezone IDs or malformed time strings return 'Error converting time: $e'; } }
Call the function using your sample values to see it in action:
void main() async { WidgetsFlutterBinding.ensureInitialized(); tz.initializeTimeZones(); // Example conversion: Bangkok → Kolkata final convertedTime = convertTimeBetweenZones( 'Asia/Bangkok', '2020-11-20 10:00 AM', 'Asia/Kolkata', ); print('Converted time: $convertedTime'); // Output will be: 2020-11-20 08:30 AM (Kolkata is 1.5 hours behind Bangkok) }
- Use Valid IANA Timezone IDs: Stick to standard IDs like
Asia/BangkokorAsia/Kolkata—avoid ambiguous abbreviations likeIST(which can mean Indian Standard Time or Irish Standard Time). - Adjust Date Formats: Modify the
DateFormatpattern if your input uses 24-hour time (e.g.,'yyyy-MM-dd HH:mm') or a different date structure. - Error Handling: Always wrap timezone operations in a try-catch block to gracefully handle typos in timezone IDs or invalid time strings.
内容的提问来源于stack exchange,提问作者chiragmevada




