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.