Dart parse full dateTime including am/pm - flutter

I have my date here 2020/07/07 09:47:54 from my API in which I'm trying to parse to 2020/07/07 09:47am. I have tried the following method using intl package but I'm getting an error
DateFormat format = DateFormat('yyyy/MM/dd hh:mm').add_jm();
DateTime newDate = format.parse(date)
Unhandled Exception: FormatException: Trying to read from 2020/07/07 09:47:54 at position 20
Anyone has an idea what seems wrong here?

I think you need to add this line of code:
String date = DateFormat.yMEd().add_jms().format(DateTime.now());
String dateWithT = date.substring(0, 8) + 'T' + date.substring(8);
DateTime dateTime = DateTime.parse(dateWithT);

Solution
I found a way in which i need to parse the string date into a DateTime format then reformat it again based on what I needed.
DateTime dateTime = DateFormat('yyyy/MM/dd h:m').parse(date);
final DateFormat formatter = DateFormat('yyyy-MM-dd h:m a');
final String formatted = formatter.format(dateTime);

You can try formatting it twice like this:
String date = '2020/07/07 09:47:54';
DateFormat myDateFormat = DateFormat('yyyy/MM/dd hh:mm');
DateTime newDate = myDateFormat.parse(date);
var myString = myDateFormat.format(newDate) + DateFormat('a').format(newDate);

Related

how to subtract two different times in flutter

I want to subtract two different times in flutter for example
String time1 = "07:00";
String time2 = "08:12";
String time3 = time2 - time1;
//result will be 01:12
this is just a sample data explanation of what I want to achieve.
See the sample code below. It prints 01:12 in the end.
Input Data:
String time1 = "07:00";
String time2 = "08:12";
Required Methods to be defined:
DateTime getTime(final String inputString) => DateFormat("hh:mm").parse(inputString);
String getString(final Duration duration) {
String formatDigits(int n) => n.toString().padLeft(2, '0');
final String minutes = formatDigits(duration.inMinutes.remainder(60));
return "${formatDigits(duration.inHours)}:$minutes";
}
Computation
final String difference = getString(getTime(time2).difference(getTime(time1)));
Printing the result
print(difference); // 01:12
Have fun - but keep in mind to change the naming of the methods to better fit into your context.
You should use Dart's built-in DateTime class and its DateTime.parse especially.
Documentation: https://api.dart.dev/stable/2.8.4/dart-core/DateTime/parse.html
Try out below code for get difference between two times.
var timeFormat = DateFormat("HH:mm"); //Time format
var first = timeFormat.parse("10:40");
var second = timeFormat.parse("18:20");
print("Difference -->${second.difference(first)}");
// prints Difference -->7:40
Flutter|Dart provides a data type to handle dates : DateTime. So instead of using String, use DateTime :
DateTime time1 = DateTime.parse(your_date_here your_time);
DateTime time2 = DateTime.parse(your_date_here your_time);
DateTime time3 = time2.difference(time1);
If you want just the time part, you can format it using DateFormat from the intl package. You'll need to import it as follows :
import 'package:intl/intl.dart';
Then do the following:
String formattedTime = DateFormat.Hms().format(time1);
String formattedTime = DateFormat.Hms().format(time2);
Or you can just directly format the result (time3):
String formattedTime = DateFormat.Hms().format(time3);

How to convert a date to local date time

I cannot change my string date to local date in dart.
What am i missing.
this is my date format i get: "2021-02-01T17:00:00.000Z"
final dateTime = DateFormat("yyyy-MM-ddTHH:mm:ssZ").parse(date, true);
var dateLocal = dateTime.toLocal();
Use the DateTime.parse method:
String givenDate = '2021-02-01T17:00:00.000Z';
DateTime localDate = DateTime.parse(givenDate).toLocal();

Datetime without 00:00:00.000 for flutter

Why everytime I make a
var date = DateTime.parse(dob);
var formattedDate = '${date.year}${date.month}${date.day}';
DateTime.parse(formattedDate)
it will still retrieve as 1961-02-26 00:00:00.000? How do I get it to become 19610226 but still in datatype DateTime?
Use DateFormat Class from intl package to format your date
var date = DateTime.parse(dob);
var dateFormatter = new DateFormat('yyyy-MM-dd');
String formattedDate = dateFormatter.format(date);
print(formattedDate); // result 2020-03-24
for more details and more formatting options see this answer

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?
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
Try this:
var df = DateFormat("h:mma");
var dt = df.parse('6:45PM');
print(DateFormat('HH:mm').format(dt));
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);
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.
Try this format:
DateFormat('HH:mm').format(DateTime.now())

convert string to datetime and compare for the 2 date diff

Question 1: I have 2 fields to let user enter start date and end date, but in string format
- DateStart (string: yyyy/mm/dd hh:mm)
- DateEnd (string: yyyy/mm/dd hh:mm)
May I how to compare both datetime? I want to know total how many hours is difference between the both date.
Question 2: user will enter 1 returnDate (string: yyyy/mm/dd hh:mm) also in string format, may I know how to update the returnDate if I will need to add 55hours on the returnDate?
Thanks
Start by taking a look at SimpleDateFormat, which will allow you to convert the String value to a Date object.
For example...
try {
// Note hh is Hour in am/pm (1-12), based on you example, it's not possible
// now the day part (ie am or pm), you could supply aa as the am/pm marker
// or use HH which is Hour in day (0-23)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm");
Date date = sdf.parse("2014/04/11 4:46");
System.out.println(date);
} catch (ParseException exp) {
exp.printStackTrace();
}
Then you can use JodaTime to calculate the difference between the two dates, see How to find difference between two Joda-Time DateTimes in minutes for an example
It should be noted that you could skip the use of SimpleDateFormat and JodaTime all the way, check out String to joda LocalDate in format of "dd-MMM-yy" for an example of converting a String to a LocalDate using JodaTime
To add time to an existing Date, you can use either Calendar or JodaTime, see how to add days to java simple date format for an example of both
I would recommend that if you are using some kind of GUI, you might consider using one of the available date pickers as it will save you a lot of hassel
I suggest using Java8's java.util.time package
Example:
public static void main(String[] args) {
// example input
String dateString1 = "2014/04/10 00:00";
String dateString2 = "2014/04/11 23:59";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
LocalDateTime date1 = LocalDateTime.parse(dateString1, dtf);
LocalDateTime date2 = LocalDateTime.parse(dateString2, dtf);
// do your stuff with the dates...
}
Here is my solution:
String date1 = "2014/04/10 15:30";
String date2 = "2014/04/11 09:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
try {
Date parsedDate1 = sdf.parse(date1);
Date parsedDate2 = sdf.parse(date2);
double secs = (parsedDate2.getTime() - parsedDate1.getTime()) / 1000;
double hours = secs / 3600;
System.out.println(hours);
} catch (ParseException e) {
e.printStackTrace();
}
For adding hours to a date:
Date date = new Date(someDateObject.getTime() + 55 * 3600 * 1000);