You can use the intl
package in Dart to format date and time variables and present them to your users in predefined pattern or in their local pattern. Here’s an example:
First, add the intl
package to your project by running the following command in your terminal:
dart pub add intl
Take into account the Locale of the User
void main() {
// Get the user's locale
final locale = Locale('en', 'US'); // For example, English (United States)
// Create a date and time
final DateTime now = DateTime.now();
// Format the date and time to a string using the user's locale
final DateFormat formatter = DateFormat.yMd(locale);
final String formattedDate = formatter.format(now);
print(formattedDate); // Output: 07/26/2024
}
In this example, the date and time are formatted to a string using the `yMd` format code. This will output the date in the format “MM/dd/yyyy”.
Here are some common format codes:
– `y`: Year (e.g., 2024)
– `M`: Month as a zero-padded number (e.g., 07)
– `d`: Day of the month as a zero-padded number (e.g., 26)
– `H`: Hour in 24-hour format as a zero-padded number (e.g., 14)
– `m`: Minute as a zero-padded number (e.g., 30)
– `s`: Second as a zero-padded number (e.g., 00)
You can combine these format codes to create more complex date and time formats.
For example, if you want the date and time in the format “July 26, 2024 2:30 PM”, you can use the following code:
final DateFormat formatter = DateFormat.EEEE, ‘MMMM d, yyyy h:mm a’, locale);
This will output the date and time in the format “Friday, July 26, 2024 2:30 PM”.
Predefined Locale for fixed Date and Tiem Format
You can use the DateFormat
class to format a date and time as a string:
import 'package:intl/intl.dart';
void main() {
final DateTime now = DateTime.now();
final String formattedDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(now);
print(formattedDate); // Output: "2024-07-26 12:00:00"
}
In this example, yyyy
represents the year as a four-digit number, MM
is the month as a zero-padded two-digit number, and HH
is the hour in 24-hour format as a zero-padded two-digit number.
Here are some common date and time formats:
yyyy-MM-dd HH:mm:ss
: “2024-07-26 12:00:00”yyyy-MM-dd HH:mm
: “2024-07-26 12:00”dd MMMM yyyy HH:mm
: “26 July 2024 12:00”
You can also use the DateTime
class to format a date and time as a string:
import 'package:intl/intl.dart';
void main() {
final DateTime now = DateTime.now();
final String formattedDate = '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day} ${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}';
print(formattedDate); // Output: "2024-07-26 12:00"
}
However, using the intl
package is generally more convenient and flexible than manually formatting dates and times.
You could check out more Flutter Articles here: https://programtom.com/dev/category/software-development/flutter/