Sanket
Sanket

Reputation: 272

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

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

Upvotes: 8

Views: 15839

Answers (6)

Vikrant S
Vikrant S

Reputation: 1

If you are using TimeOfDay,

var time = await showTimePicker(context: context, initialTime: TimeOfDay.now());
String formattedTime ='${time.hour}:${time.minute}';

Upvotes: 0

Bijoya_Banik
Bijoya_Banik

Reputation: 449

Try this format:

DateFormat('HH:mm').format(DateTime.now())

Upvotes: 2

Dhyan V
Dhyan V

Reputation: 651

If you are using TimeOfDay you can easily convert it into 24 hour by using the following code

TimeOfDay? selectedTime = TimeOfDay.now();

var replacingTime = selectedTime!.replacing(
                            hour: selectedTime!.hour,
                            minute: selectedTime!.minute);

String formattedTime = replacingTime.hour.toString() +
                                ":" +
                                replacingTime.minute.toString();

this worked for me.

Upvotes: 0

Tinus Jackson
Tinus Jackson

Reputation: 3653

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

Upvotes: 31

nirkov
nirkov

Reputation: 809

In case of "hh:mm:ssPM" or "hh:mm:ssAM" -

String [] splitedString = yourString.split(":");
String newFormat = splitedString[2].contain("PM") ? String.valueOf(Integer.parseInt(splitedString[0]) + 12) : splitedString[0] + ":" + splitedString[1] + ":" + splitedString[2].substring(0,2);

Upvotes: 1

Coeus.D
Coeus.D

Reputation: 979

Try this:

 var df =  DateFormat("h:mma");
 var dt = df.parse('6:45PM');
 print(DateFormat('HH:mm').format(dt));

Upvotes: 6

Related Questions