Giter Club home page Giter Club logo

time.dart's Introduction

⏰ 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.1.4"

⚡ 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,
);

Visit the API Reference to find out all that is available.

🐛 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

time.dart's People

Contributors

brianegan avatar definitelyokay avatar erluxman avatar fmorschel avatar jodinathan avatar jogboms avatar jporsay avatar matuella avatar mnordine avatar paitomax avatar shinriyo avatar slightfoot avatar timwhiting avatar wilkomanger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

time.dart's Issues

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?

Please increment the package major version for breaking changes

In #8 there was a breaking change. In 0300e03 it was documented as a breaking change with a feature version bump.

See https://dart.dev/tools/pub/versioning#semantic-versions and https://semver.org/ for info on semantic versioning. By incrementing the major version to 2.0.0, downstream consumers of your package can avoid getting broken by changes like this.

It can be smoother to also have a migration period where things are not broken, but you can update to the new name in advance. In this case the getter could have been forwarded with a new name and the old one marked @deprecated.

  /// Adds the Duration to the current DateTime and returns a DateTime in the future
  DateTime get fromNow => DateTime.now() + this;

  @Deprecated('Use fromNow instead. Will be removed in 2.0.0')
  DateTime get later => fromNow;

It would be a good idea to add back this definition of later and publish as version 1.1.1 - a bug fix release to undo the breaking change.

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

copyWith ignores isUtc field

  test('copyWith should save isUtc', () async {
      final now = DateTime.now().toUtc();
      expect(now.isUtc, isTrue);

      final later = now.copyWith(hour: now.hour + 3);
      expect(later.isUtc, isTrue);
    });

copyWith method

Do you think this library would be a good place for a copyWith method?

extension DateTimeExtension on DateTime {
  DateTime copyWith({
    int year,
    int month,
    int day,
    int hour,
    int minute,
    int second,
    int millisecond,
    int microsecond,
  }) {
    return DateTime(
      year ?? this.year,
      month ?? this.month,
      day ?? this.day,
      hour ?? this.hour,
      minute ?? this.minute,
      second ?? this.second,
      millisecond ?? this.millisecond,
      microsecond ?? this.microsecond,
    );
  }
}

[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;
    }
  }
}

Mergin your code with dartx

Hey @jogboms !

You work here is great! There is a library called dartx that has a proposal to add a lot of extensions to the dart's types. Since they were missing the time extensions I made a pull request to their repostory with your work.

I gave you credits on readme. Take a look and tell what you think: simc/dartx#11

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.

[Feature Request]age calculation

Do you think about age calculation feature for it?
Converting DateTime birthday to int age.
East Asian age reckoning option also.

[Feature Request] New methods on DateTime (firstDayOfMonth, lastDayOfMonth, lastDayOfWeek, firstDayOfWeek, firstDayOfYear, lastDayOfYear)

Looking for lastDayOfMonth like feature, found this StackOverflow question and I really liked the way Yogesh Parwani mixed Chris Buckett and Kai Sellgren awnsers. As pointed by Juniper Belmont on Buckett's answer, I do think this could be a new feature as mnordine suggested here.

(Better code from here - lrhn)

Code bellow:

extension DateTimeFirstLast on DateTime {
  DateTime get firstDayOfWeek => DateTime.utc(year, month, day + 1 - weekday);
  DateTime get lastDayOfWeek => DateTime.utc(year, month, day + 7 - weekday);  
  DateTime get firstDayOfMonth => DateTime.utc(year, month, 1);
  DateTime get lastDayOfMonth => DateTime.utc(year, month + 1, 0);
  DateTime get firstDayOfYear => DateTime.utc(year, 1, 1);
  DateTime get lastDayOfYear => DateTime.utc(year, 12, 31);
}

[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)

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)?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.