Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a String like this "6:45AM" then how can i convert it into 24-hour TimeOfDay or DateTime format

Tags:

flutter

dart

I want to convert a string (12 hour) "6:45PM" into a 18:45:00 (24 hour) TimeOfDay Format, how can be this done?

like image 337
Sanket Avatar asked Jul 19 '19 09:07

Sanket


People also ask

How do you convert a string to a time?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do I convert a date to 24 hour format?

We can change the pattern in the SimpleDateFormat for the conversion. The pattern dd/MM/yyyy hh:mm:ss aa is used for the 12 hour format and the pattern MM-dd-yyyy HH:mm:ss is used for the 24 hour format.

How do you convert strings from mm/dd/yyyy to date?

string strDate = DateTime. Now. ToString("MM/dd/yyyy");

How do you convert 12 hours to 24 hour flutter?

Flutter Convert TimeOfDay to 24 hours format | Technical Feeder. final time = TimeOfDay(hour: 21, minute: 12); time. toString(); // TimeOfDay(21:12) We expect that it returns hh:mm format but actually not.


1 Answers

You can try to use a DateFormat, just include intl dependency to your pubspec.yaml

First parse the value to a date, then format it how you want

import 'package:intl/intl.dart';
// parse date
DateTime date= DateFormat.jm().parse("6:45 PM");
DateTime date2= DateFormat("hh:mma").parse("6:45PM"); // think this will work better for you
// format date
print(DateFormat("HH:mm").format(date));
print(DateFormat("HH:mm").format(date2));

References

  • DateTime
  • intl package
like image 95
Tinus Jackson Avatar answered Nov 15 '22 10:11

Tinus Jackson