Working with dates and times

Proper date-time handling is needed in almost every data context. What does Dart give us to ease working with dates and times? Dart has the excellent built-in classes DateTime and Duration in dart:core. As a few of its many uses, you can do the following:

  • Compare and calculate with date times
  • Get every part of a date-time
  • Work with different time zones
  • Measure timespans with Stopwatch

However, the DateTime class does not provide internationalization; for this purpose, you need to use the intl package from the Dart team.

How to do it...

The following are some useful techniques (try them out in date_time.dart):

  • Formatting dates (from DateTime to a string) to standard formats, but also to any format using the package intl, as shown in the following code:
    import 'package:intl/intl.dart';
    import 'package:intl/date_symbol_data_local.dart';
    
      print(now.toIso8601String()); // 2014-05-08T14:03:21.238
      print(now.toLocal());         // 2014-05-08 14:03:21.238
      print(now.toString());        // 2014-05-08 14:03:21.238
      print(now.toUtc());           // 2014-05-08 12:03:21.238Z
      // using intl to format:
      var formatter = new DateFormat('yyyy-MM-dd'),
      String formatted = formatter.format(now);
      print(formatted); // 2014-05-08
      print(new DateFormat("EEEEE").format(now)); // Thursday
      print(new DateFormat("yMMMMEEEEd").format(now));              // Thursday, May 8, 2014
      print(new DateFormat("y-MM-E-d").format(now));             // 2014-05-Thu-8
      print(new DateFormat("jms").format(now)); // 2:19:08 PM
      print(new DateFormat('dd/MMM/y HH:mm:ss').format(now));    // 08/May/2014 14:39:07
      // locale data:
      initializeDateFormatting("fr_FR", null).then(formatDates);
    // …
    }
    
    formatDates (var d) {
        print(new DateFormat("EEEEE", 'fr_FR').format(now));      // jeudi
        print(new DateFormat("yMMMMEEEEd", 'fr_FR').format(now)); // jeudi 8 mai 2014
        print(new DateFormat("y-MM-E-d", 'fr_FR').format(now));   // 2014-05-jeu.-8
    }
  • Parsing dates (from a string to a DateTime) when the given string is not in one of the acceptable date formats; an exception is thrown and caught as shown in the following code:
      try {
        DateTime dt = DateTime.parse("2014-05-08T15+02:00");
      } on FormatException catch(e) {
        print('FormatException: $e'),
      }
  • Working with timezone information:
    print(now.toLocal());// time in local timezone
    print(now.toUtc());  // time in Coordinated Universal Time
    print(now.timeZoneName);   // Romance (zomertijd)
    print(now.timeZoneOffset); // 2:00:00.000
    000
    
  • Finding the last day of the month can be done as follows:
       var date = new DateTime(2014,6,0);
       print(date.day);  // 31 
       // more general:
    var lastDayDateTime = (now.month < 12) ?              new DateTime(now.year, now.month + 1, 0)                   : new DateTime(now.year + 1, 1, 0);
       print(lastDayDateTime.day); // 31

How it works...

Formatting a DateTime instance can be done with a few to… methods from dart:core, such as toLocal() to get the time in the local time zones (as defined by your machine). However, intl gives you much more flexibility; make a DateFormat object with the specific format string as an argument, and then call the format method to get a formatted string back.

For example, d gives the day number, E gives the weekday in an abbreviated form, EE gives the full day's name, M gives the month number, y gives the year, H gives the hour (0-24), j gives the hour (0-12) with AM or PM, m gives the minute, and so on. Many format combinations are possible (and you can build your own).

Note

For a complete overview of format combinations, refer to https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/intl/intl.DateFormat.

If you want formatting for a particular locale (such as be_NL, cs_CZ, de_DE, and so on), you must first load the specific locale data by importing date_symbol_data_local.dart and then calling initializeDateFormatting. The first parameter is the specific locale. If you give it the value null, all the available locale data is loaded, as shown in the following code:

initializeDateFormatting("fr_FR", null).then(formatDates);

Next, when constructing the DateFormat object, the locale (such as 'fr_FR') has to be given as the second parameter:

new DateFormat("yMMMMEEEEd", 'fr_FR')

The formatDates method shows the following code in action:

formatDates (var d) {
    print(new DateFormat("EEEEE", 'fr_FR').format(now)); // jeudi
    print(new DateFormat("yMMMMEEEEd", 'fr_FR').format(now)); // jeudi 8 mai 2014
    print(new DateFormat("y-MM-E-d", 'fr_FR').format(now)); // 2014-05-jeu.-8
}

Parsing a well-formed string into a DateTime string is done with the static DateTime.parse method, which takes the string and produces DateTime. The input format must conform to an ISO 8601 format. If the input format cannot be parsed, FormatException is thrown, so use try/catch to handle this.

The toUTC option gives you the time in Coordinated Universal Time (UTC) format, which is for all practical purposes identical to Greenwich Mean Time (GMT). Use timeZoneName to get an abbreviated name of the time zone for the DateTime object. The difference between UTC and the time zone of a DateTime object is calculated by calling timeZoneOffset.

To find the last day of the month, giving a day value of zero for the next month returns the previous month's last day.

There's more...

Be aware that a DateTime object is always in the local time zone, unless explicitly created in the UTC time zone with the DateTime.utc constructor; this can be done as follows:

DateTime moonLanding  = new DateTime.utc(1969, DateTime.JULY, 20);

In this constructor, only the year is required, all the other date and time parts are optional.

If you have other Datetime questions, look up the API docs at https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.DateTime

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset