⏰ Type-safe DateTime and Duration calculations, powered by extensions.

Overview

Time

Build codecov pub package

With shiny extensions, if you have ever written something like this, then look no further:

final DateTime fourHoursFromNow = DateTime.now() + Duration(hours: 4);

🎖 Installation

dependencies:
  time: "^2.0.1"

Import

import 'package:time/time.dart';

🎮 Usage

final Duration tenMinutes = 10.minutes;
final Duration oneHourThirtyMinutes = 1.5.hours;
final DateTime afterTenMinutes = DateTime.now() + 10.minutes;
final Duration tenMinutesAndSome = 10.minutes + 15.seconds;
final int tenMinutesInSeconds = 10.minutes.inSeconds;
final DateTime tenMinutesFromNow = 10.minutes.fromNow;

You can perform all basic arithmetic operations on Duration as you always have been:

final Duration interval = 10.minutes + 15.seconds - 3.minutes + 2.hours;
final Duration doubled = interval * 2;

You can also use these operations on DateTime:

final DateTime oneHourAfter = DateTime() + 1.hours;

Duration is easily convertible as it always has been:

final int twoMinutesInSeconds = 2.minutes.inSeconds;

You can also convert Duration to DateTime, if needed:

final DateTime timeInFuture = 5.minutes.fromNow;
final DateTime timeInPast = 5.minutes.ago;

Iterate through a DateTime range:

final DateTime start = DateTime(2019, 12, 2);
final DateTime end = start + 1.weeks;
final DateTime tuesday = start.to(end).firstWhere((date) => date.weekday == DateTime.tuesday);

Granular comparison between DateTime fields:

final DateTime specificDate = DateTime(2021, 01, 01);
final DateTime otherDate = DateTime(2021, 02, 01);

print(specificDate.isAtSameYearAs(otherDate)); // true
print(specificDate.isAtSameMonthAs(otherDate)); // false
print(specificDate.isAtSameDayAs(otherDate)); // false

You can also delay code execution:

void doSomething() async {
  await 5.seconds.delay;
  // Do the other things
}

You can also use the popular copyWith:

final initial = DateTime(2019, 2, 4, 24, 50, 45, 1, 1);
final expected = initial.copyWith(
  year: 2021,
  month: 10,
  day: 28,
  hour: 12,
  minute: 45,
  second: 10,
  millisecond: 0,
  microsecond: 12,
);

🐛 Bugs/Requests

If you encounter any problems feel free to open an issue. If you feel the library is missing a feature, please raise a ticket on Github and I'll look into it. Pull request are also welcome.

👏 Inspiration

  • Swift library of the same name - Time.
  • Kotlin library of the same name - Time.

License

MIT License

Comments
  • [Feature]judge today, yesterday, tomorrow methods

    [Feature]judge today, yesterday, tomorrow methods

    Do you want these?

    If so, I will pull-request.

    someDateTimeValue.isToday();
    
    => true or false
    
    someDateTimeValue.isTomorrow();
    
    => true or false
    
    someDateTimeValue.isYesterday();
    
    => true or false
    
    opened by shinriyo 8
  • [Feature Request] Get only date or only time

    [Feature Request] Get only date or only time

    In C#, we have those two usefull properties of a DateTime:

    var now = DateTime.Now; // 2020-04-10T15:27:00
    var datePartOnly = now.Date; // 2020-03-10T00:00:00 (returns a DateTime, with 00:00:00 time)
    var timePartOnly = now.TimeOfDay; // 15:17:00 (returns a TimeSpan - Duration in Dart)
    
    opened by JCKodel 8
  • Fix wrong assertion when equal

    Fix wrong assertion when equal

    Found a bug. When both min and max were equal, the assertion was throwing. Added a test to maintain that as well. The documentation above was correct, must have missed it when publishing the first time.

    opened by FMorschel 4
  • Shorthand for .difference(DateTime.now())

    Shorthand for .difference(DateTime.now())

    I dislike writing .difference(DateTime.now()). On the homepage of the package I didn't find a shorthand for that expression in this package? Does one exist (and maybe might be made easier to find)?

    needs-refinement 
    opened by ChristianKleineidam 4
  • Rename later to fromNow to clarify the origin time

    Rename later to fromNow to clarify the origin time

    Using .later doesn't leave clear what the origin time is. Renamed it to .fromNow to clarify that the time is a delta time starting from DateTime.now().

    3rd party examples: moment.js uses a similar nomenclature. As does Ruby on Rails.

    Fixes #9

    opened by jporsay 3
  • Use clock package to allow for easier testing.

    Use clock package to allow for easier testing.

    This PR allows the Time package to use the official clock package published by the Dart tools team. By using clock.now() instead of DateTime.now(), code which is time-dependent can be easily tested using the clock package's withClock test utility function.

    Here's a lovely article about using the clock package to test time-dependent code.

    This also makes the unit tests here a little bit cleaner. If you have any feedback, let me know! Thank you for making this package.

    opened by definitelyokay 2
  • Add season extension

    Add season extension

    Adds two new getters to DateTime instances.

    DateTime(2001,6, 26).seasonNorth  //  Season.summer
    DateTime(2001,6, 26).seasonSouth  // Season.winter
    

    I couldn't decide if I should create this in a separate package or include this here. So I need your verdict, If you find reasonable adding a season extension to the package, this is ok. If not, just tell me and I publish it separately.

    opened by renancaraujo 2
  • Added config files for project line length

    Added config files for project line length

    Since my last contribution, I figured I could suggest these files so that people using VSCode or Android Studio/IntelliJ that work on this project will always get the right line length for dart formatting.

    opened by FMorschel 1
  • [Feature Request] DateTime clamp

    [Feature Request] DateTime clamp

    Proposal

    DateTime (maybe Duration as well?) clamp. Any suggestions are welcome. I just encountered a need for a DateTime clamp, perhaps this nullable option is not the best fit, but for my case it was.

    Inspiration

    num clamp(num lowerLimit, num upperLimit);
    

    Actual implementation

    extension ClampDateTime on DateTime {
      DateTime clamp({DateTime? min, DateTime? max}) {
        assert(
          ((min != null) && (max != null)) ? min.compareTo(max).isNegative : true,
          'DateTime min has to be before max\n(min: $min - max: $max)',
        );
        if ((min != null) && compareTo(min).isNegative) {
          return min;
        } else if ((max != null) && max.compareTo(this).isNegative) {
          return max;
        } else {
          return this;
        }
      }
    }
    
    extension DurationClamp on Duration{
      Duration clamp({Duration? min, Duration? max}) {
        assert(
          ((min != null) && (max != null)) ? min.compareTo(max).isNegative : true,
          'Duration min has to be shorter than max\n(min: $min - max: $max)',
        );
        if ((min != null) && compareTo(min).isNegative) {
          return min;
        } else if ((max != null) && max.compareTo(this).isNegative) {
          return max;
        } else {
          return this;
        }
      }
    }
    
    opened by FMorschel 1
  • Migrate to null-safety

    Migrate to null-safety

    This package is currently blocking dartx from migrating to null-safety. Null-safety is now in beta, and the dart team is encouraging package authors to migrate now. I'll submit a pull request if you'd like to review it. I see there is one already open, but it doesn't bump the dart sdk min version to 2.12 like we are supposed to, and instead enables it in the analysis_options.yaml which is not required if you set the min sdk version properly.

    opened by TimWhiting 1
  • New release?

    New release?

    Hi!

    I see there are a number of handy things on master that were not cut into a new release - especially DateTime().now.date / wasYesterday and other.

    Anything against releasing a new version?

    opened by dgilperez 1
  • add isAfterMonth isAfterDay isBeforeMonth isBeforeDay

    add isAfterMonth isAfterDay isBeforeMonth isBeforeDay

    DateTIme class has isAfter isBefore
    but There is no API to determine whether a given date is after or before the day after or before the day before. also month

    final DateTime specificDate = DateTime(2021, 01, 01);
    final DateTime sameDate = DateTime(2021, 01, 01).add(const Duration(seconds: 5));
    final DateTime otherDate = DateTime(2021, 01, 02);
    
    print(specificDate.isAfterDay(sameDate)); // false
    print(specificDate.isAfterDay(otherDate)); // true
    
    opened by utamori 0
Releases(v2.1.3)
  • v2.1.3(Sep 3, 2022)

    What's Changed

    • isWorkday and isWeekday by @FMorschel in https://github.com/jogboms/time.dart/pull/65

    Full Changelog: https://github.com/jogboms/time.dart/compare/v2.1.2...v2.1.3

    Source code(tar.gz)
    Source code(zip)
  • v2.1.2(Aug 23, 2022)

    What's Changed

    • Handle UTC during date by @Paitomax in https://github.com/jogboms/time.dart/pull/60
    • Fix wrong assertion when equal by @FMorschel in https://github.com/jogboms/time.dart/pull/61
    • Fix Duration.clamp min=max bug by @FMorschel in https://github.com/jogboms/time.dart/pull/63

    New Contributors

    • @Paitomax made their first contribution in https://github.com/jogboms/time.dart/pull/60

    Full Changelog: https://github.com/jogboms/time.dart/compare/v2.1.1...v2.1.2

    Source code(tar.gz)
    Source code(zip)
  • v2.1.1(Jun 4, 2022)

    What's Changed

    • First and Last days extensions added by @FMorschel in https://github.com/jogboms/time.dart/pull/51
    • Clamp functions added to Duration and DateTime by @FMorschel in https://github.com/jogboms/time.dart/pull/53

    New Contributors

    • @FMorschel made their first contribution in https://github.com/jogboms/time.dart/pull/51

    Full Changelog: https://github.com/jogboms/time.dart/compare/v2.1.0...v2.1.1

    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Dec 8, 2021)

  • v2.0.1(Nov 14, 2021)

  • v2.0.0(Mar 5, 2021)

  • v1.4.1(Mar 5, 2021)

    • Introduce isAtSameYearAs extension to DateTime
    • Introduce isAtSameMonthAs extension to DateTime
    • Introduce isAtSameDayAs extension to DateTime
    • Introduce isAtSameHourAs extension to DateTime
    • Introduce isAtSameMinuteAs extension to DateTime
    • Introduce isAtSameMillisecondAs extension to DateTime
    • Introduce isAtSameMicrosecondAs extension to DateTime
    Source code(tar.gz)
    Source code(zip)
  • 1.5.0-nullsafety.0(Nov 24, 2020)

  • v1.4.0(Nov 24, 2020)

  • v1.3.0(Apr 3, 2020)

  • v1.2.0(Dec 4, 2019)

    • Iterate through a DateTime range:
    final DateTime start = DateTime(2019, 12, 2);
    final DateTime end = start + 1.weeks;
    final DateTime tuesday = start.to(end).firstWhere((date) => date.weekday == DateTime.tuesday);
    
    Source code(tar.gz)
    Source code(zip)
  • v1.1.1(Nov 19, 2019)

Owner
Jeremiah Ogbomo
Think. Code. Love.
Jeremiah Ogbomo
Datetime picker formfield - A Flutter widget that wraps a TextFormField and integrates the date and/or time picker dialogs.

DateTimeField A TextFormField that emits DateTimes and helps show Material, Cupertino, and other style picker dialogs. Example See the example tab (ex

Jacob Phillips 182 Dec 1, 2022
A pure dart package with collection of Nepali Utilities like Date converter, Date formatter, DateTime, Nepali Numbers, Nepali Unicode, Nepali Moments and many more.

Nepali Utilities for Dart A pure dart package with collection of Nepali Utilities like Date converter, Date formatter, DateTime, Nepali Number, Nepali

Sarbagya Dhaubanjar 23 Nov 22, 2022
A DateTime picker that lets user to select a date and the time, with start & end as a range

Omni DateTime Picker A DateTime picker that lets user to select a date and the time, with start & end as a range. Screenshots Getting started Add this

null 17 Dec 29, 2022
A Flutter package for using Jalali (Shamsi, Solar, Persian or Jalaali) calendar. You can convert, format and manipulate Jalali and Gregorian (Miladi) dates.

A Flutter package for using Jalali (Shamsi, Solar, Persian or Jalaali) calendar. You can convert, format and manipulate Jalali and Gregorian (Miladi) dates.

Amirreza Madani 63 Dec 21, 2022
A day night time picker for Flutter. Beautiful day and night animation with Sun and Moon assets.

DayNightTimePicker A day night time picker for Flutter with Zero Dependencies. Default style: IOS style: View it on pub.dev Installation Add to pubspe

Subhamay Dutta 68 Dec 29, 2022
Make a timer application with a fancy neon effect and beautiful UI

Make a timer application with a fancy neon effect and beautiful UI

null 6 Dec 25, 2021
Easy to use and beautiful calendar strip component for Flutter.

Flutter Calendar Strip Easy to use and beautiful calendar strip component for Flutter. Awesome celender widget If this project has helped you out, ple

Siddharth V 176 Dec 14, 2022
A Flutter package allows you to easily implement all calendar UI and calendar event functionality. 👌🔝🎉

calendar_view A Flutter package allows you to easily implement all calendar UI and calendar event functionality. For web demo visit Calendar View Exam

Simform Solutions 219 Dec 22, 2022
Flutter calendar app. register schedule and manage in calendar ui.

flutter calendar app. register schedule and manage in calendar ui. save schedule data in firestore. and create widget and read schedule from firestore in widget.

akiho 11 Oct 30, 2022
CalendarDatePicker2 - A lightweight and customizable calendar picker based on Flutter CalendarDatePicker

A lightweight and customizable calendar picker based on Flutter CalendarDatePicker, with support for single date picker, range picker and multi picker.

Neo Liu 27 Dec 22, 2022
Fluboard - Calendar wall-board-display built with Flutter and ❤️

Fluboard Calendar wall-board-display built with Flutter and ❤️ Goals Build calendar board (DAKBoard alternative) which easy to install and easy to cus

iTeqno 10 Dec 27, 2022
Serialize almost everything you ever need! 📦 Supports serializing MaterialColor, Color, Size, Locale, IconData, UuidValue, DateTime, Directory, File, Duration, and many more.

osum_serializable The goal is to serialize almost everything you ever need! json_serializable is an amazing package to serialize classes but cannot se

Aswin Murali 2 Sep 23, 2022
A persian (farsi,shamsi) datetime picker for flutter, inspired by material datetime picker.

?? A persian (farsi,shamsi) datetime picker for flutter, inspired by material datetime picker. Persian datetime picker inspired by material datetime p

Persian Flutter Community 142 Dec 19, 2022
Dart duration iso parser - Package to parse duration from ISO 8601 string

duration_iso_parser Package for parsing ISO 8601 durations string to the Duratio

Innim 1 Jan 18, 2022
A type-safe command-line parsing library for Dart

plade Plade is a type-safe CLI parsing library for Dart. Highlights Fully type-safe and null-safe. Support for a variety of different parsing styles (

Ryan Gonzalez 6 Jan 1, 2022
Shared preferences typed - A type-safe wrapper around shared preferences, inspired by ts-localstorage

Typed Shared Preferences A type-safe wrapper around shared_preferences, inspired

Philipp Bauer 0 Jan 31, 2022
Safe is an open source mobile platorm to discretely capture incidents with ease, powered by an SMCE written in native Swift and Kotlin.

Safe A powerful tool for personal and community safety. joinsafe.me » Available for iOS & Android ~ Links will be added once a release is available. ~

Safe 10 Oct 26, 2022
Datetime picker formfield - A Flutter widget that wraps a TextFormField and integrates the date and/or time picker dialogs.

DateTimeField A TextFormField that emits DateTimes and helps show Material, Cupertino, and other style picker dialogs. Example See the example tab (ex

Jacob Phillips 182 Dec 1, 2022
A JSON serialize class to convert 'to' and 'from' JSON format Enums, DateTime and any of your own classes.

A JSON serialize class to convert 'to' and 'from' JSON format Enums, DateTime and any of your own classes. Introduction Jsonize solves the problem of

null 2 Nov 17, 2022
Widget for displaying waves with custom color, duration, floating and blur effects.

Wave Widget for displaying waves with custom color, duration, floating and blur effects. Getting Started WaveWidget( config: CustomConfig(

Protoss 890 Dec 31, 2022