0

I have 2 times which I need to do subtract and I am almost close but there is one big issue

I have 2 times in string-like 10:00AM and 10:00PM

And my code is this

   var df =  DateFormat("hh:mm");                                           
   var durationStart =  DateFormat('HH:mm').format(df.parse(10:00AM));
   var durationEnd =  DateFormat('HH:mm').format(df.parse(10:00PM));
  
   print('durationStart ${durationStart}');
   print('durationEnd ${durationEnd}');


   var Startparts = durationStart.split(':');
   var startDurationSet = Duration(hours: int.parse(Startparts[0].trim()), minutes: int.parse(Startparts[1].trim()));


   var Endparts = durationEnd.split(':');
   var endDurationSet = Duration(hours: int.parse(Endparts[0].trim()), minutes: int.parse(Endparts[1].trim()));


   print('startDurationSet ${startDurationSet}');

   var result = Duration(hours: int.parse(Endparts[0].trim()) - int.parse(Startparts[0].trim()) , minutes: int.parse(Startparts[1].trim()) - int.parse(Endparts[1].trim()));
    
       print('result ${result.toString().replaceAll('-', '')}');

So I have 2 times one is startTime and one is End time. I simply need a difference between hours. for example, I have 10:00Am and 01:00PM i need 3hours but it's showing 9hours. But what I am receiving is if I have 10:00AM and 10:00pm it's showing 0 hours but its needs to show 12. Same

rameez khan
  • 73
  • 1
  • 23
  • 68

6 Answers6

3

It is easy if you can get your start and end date in DateTime properly

Hint, I use "hh:mma" since that is your original format => "10:00AM"

If I use "HH:mm" like you do, i'll always get the same time since it doesn't parse the AM/PM after the 10:00

// Get your time in term of date time

DateTime startDate = DateFormat("hh:mma").parse("10:00AM");
DateTime endDate = DateFormat("hh:mma").parse("10:00PM");


// Get the Duration using the diferrence method

Duration dif = endDate.difference(startDate);

// Print the result in any format you want
print(dif.toString(); // 12:00:00.000000
print(dif.inHours); // 12

Farhan Syah
  • 753
  • 3
  • 14
0

Are you looking for something like this?

TimeOfDay _calcTimeOfDay(int hour, int minute) {
    if (minute > 60) {
      minute = (minute % 60);
      hour += 1;
    }

    return TimeOfDay(hour: hour, minute: minute);
}

The problem is if you have hour=24 and minute=75 then the hour would be 25, which is not a valid hour.

Not sure I fully understand the question, maybe if you can provide more info.

Hesam Chobanlou
  • 331
  • 1
  • 3
0

What you need to add on your DateFormat is the code for am/pm marker: a. Using either format hh:mma or h:ma should work.

You can then use DateTime.difference() to calculate the time variance from durationStart and durationEnd. Here's a sample that you can run on DartPad.

import 'package:intl/intl.dart';
void main() {
  /// Set the format that of the Date/Time that like to parse
  /// h - 12h in am/pm
  /// m - minute in hour
  /// a - am/pm marker
  /// See more format here: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html
  var dateFormat =  DateFormat('h:ma');                                           
  DateTime durationStart =  dateFormat.parse('10:00AM');
  DateTime durationEnd =  dateFormat.parse('10:00PM');
  
  print('durationStart: $durationStart');
  print('durationEnd: $durationEnd');
  
  /// Fetch the difference using DateTime.difference()
  /// https://api.flutter.dev/flutter/dart-core/DateTime/difference.html
  print('difference: ${durationEnd.difference(durationStart).inHours}');
}
Omatt
  • 8,564
  • 2
  • 42
  • 144
0

Use package

intl: ^0.17.0

import 'package:intl/intl.dart';

 var dateFormat = DateFormat('h:ma');
  DateTime durationStart = dateFormat.parse('10:00AM');
  DateTime durationEnd = dateFormat.parse('1:00PM');

  print('durationStart: $durationStart');
  print('durationEnd: $durationEnd');

  var differenceInHours = durationEnd.difference(durationStart).inHours;

  print('difference: $differenceInHours hours');

enter image description here

Prajeet Naga
  • 214
  • 1
  • 7
0

I have created one class for you:

import 'package:intl/intl.dart';

class DateUtils {
  static String getTimeDifference(String startTime, String endTime){
    /// Set the format that of the Date/Time that like to parse
    /// h - 12h in am/pm
    /// m - minute in hour
    /// a - am/pm marker
    /// See more format here: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html
    var dateFormat =  DateFormat('h:ma');
    DateTime durationStart =  dateFormat.parse(startTime);
    DateTime durationEnd =  dateFormat.parse(endTime);

    return '${durationEnd.difference(durationStart).inHours} hours';
  }
}

How you can use:

void main() {
  print("10:00PM, 10:30PM => " + DateUtils.getTimeDifference("10:00PM", "10:30PM"));
  print("12:00AM, 04:00AM => " + DateUtils.getTimeDifference("12:00AM", "04:00AM"));
  print("01:00AM, 03:00AM => " + DateUtils.getTimeDifference("01:00AM", "03:00AM"));
  print("12:00AM, 06:00PM => " + DateUtils.getTimeDifference("12:00AM", "06:00PM"));
  print("04:00PM, 03:00PM => " + DateUtils.getTimeDifference("04:00PM", "03:00PM"));
}

Output:

10:00PM, 10:30PM => 0 hours
12:00AM, 04:00AM => 4 hours
01:00AM, 03:00AM => 2 hours
12:00AM, 06:00PM => 18 hours
04:00PM, 03:00PM => -1 hours

Hope it will be helpful.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
0

create extension for Duration class:

extension DurationSubtraction on Duration {
      Duration subtractSeconds(Duration other) {
        return Duration(
          seconds: this.inSeconds - other.inSeconds,
        );
      }

      Duration addSeconds(Duration other) {
        return Duration(
          seconds: this.inSeconds + other.inSeconds,
        );
      }
  
}

and use as below:

Duration _currentDuration = const Duration();
final skipDuration = const Duration(seconds: 10);

Duration subractedDuration = _currentDuration.subtractSeconds(skipDuration)

Note: Don't add/subtract all attributes e.g. seconds, minutes, hours with same method, updating any single property will change the rest of them.

Asad
  • 1,241
  • 3
  • 19
  • 32