This is the first day of my participation in the August More Text challenge. Time stamps are often encountered in daily project development in response to the August challenge

The date is converted to a timestamp in the Flutter Dart

var now = new DateTime.now(); print(now.millisecondsSinceEpoch); // In milliseconds with a 13-bit timestampCopy the code

The timestamp is converted to a date in the Flutter Dart

var now = new DateTime.now(); var a=now.millisecondsSinceEpoch; / / the time stamp print (DateTime fromMillisecondsSinceEpoch (a));Copy the code

Dart’s date type has some similarities with JS, but there are some big differences, too, and I personally feel it’s a little more useful than the JS API. Dart’s date object is DateTime, and let’s walk through the use of its API step by step.

Get the current time

DateTime nowTime = DateTime.now();
Copy the code

This gets the current time object, which provides the API for the current time, year, month, day, etc. :

nowTime.year ; NowTime / / 2020. The month; //6(js starts from 0, dart starts from 1, we don't need to add one) / / 6 nowTime. Hour; / / 6 nowTime. Minute; / / 6 nowTime. Second; / / 6 seconds nowTime. Millisecond; / / 346 milliseconds nowTime. MillisecondsSinceEpoch; / / 13 timestamp, usually using time in js. GetTime () to get to is 13 nowTime microsecondsSinceEpoch; // 16-bit timestamp nowtime.toISO8601String (); //2020-06-22T17:52:17.108937 Output format ISO8601 Standard time format nowtime.toutc ().tostring (); //2020-06-22 09:53:26.373952z //2020-06-22 09:53:26.373952z //2020-06-22 09:53:26.373952 Outputs the current local time (not absolute), with the difference from UTC time is not followed by Z nowtime.tolocal ().tostring (); Output the current local timeCopy the code

Both toUtc and toLocal apis return a DateTime object. The toString method is used as a direct output, so the toString method returns the local time by default. If converted toUtc, A call to toString returns the string format of the UTC time. We can see this in more detail in the parse string below.

Parsing string time

In network data transmission, time is usually a string, which requires time parsing. Dart provides corresponding APIS for us:

DateTime now = DateTime.parse("2020-06-22 09:53:26");
Copy the code

In this case, if we input UTC time, toString will output UTC time, and if we input local time, toString will output local time. We need to make a distinction here, so when we need a string format, it’s best to call the relevant API.

Parse can also parse relevant time zones to convert time:

DateTime now = DateTime.parse("2020-06-22 09:53:26+0800");
Copy the code

This time represents the time of the eighth ward east.

Set a time

Dart provides an API for setting the time, but I personally find it tedious. This method is more cumbersome than using string formatting, so let’s take a look

DateTime now = DateTime(2020, 6, 22, 16, 37 , 16); DateTime nowUtc = DateTime.utc(2020, 6, 22, 16, 37 , 16); / / utc timeCopy the code

It is ok to transmit the time of year, month, day, minute and second in turn. It may be better to use this method for setting time in some business scenarios. I have not used it so far, which feels very troublesome.

Calculation of time

Dart provides a convenient method for adding or subtracting an hour in time:

DateTime now = DateTime.now(); DateTime a = now.add(Duration(days:1,minutes: 10)); DateTime a = now.add(Duration(days:1,minutes: -10)); // Add one day minus 10 minutes to the current timeCopy the code

Other year, month, day, hour, minute, second method is the same, do not repeat.

Comparison of time

I personally prefer to use timestamps for comparison. Dart also provides an API for comparison, so let’s take a look:

DateTime d1 = new DateTime(2020, 6, 20); DateTime d2 = new DateTime(2020, 7, 20); DateTime d3 = new DateTime(2020, 6, 20); print(d1.isAfter(d2)); False print(d1.isbefore (d2)); True print(d1.isAtSameMomentAs(d3)); // Is the same as trueCopy the code

Dart also provides a method for calculating the two time differences, which is useful, so let’s take a look

DateTime d4 = new DateTime(2020, 6, 19, 16 , 30); DateTime d5 = new DateTime(2020, 6, 20, 15, 20); var difference = d5.difference(d4); print([difference.inDays, difference.inHours,difference.inMinutes]); // Number of days, hours, minutes between d4 and D5 [0, 22, 1370]Copy the code

String formatting date

In the application, to format the character is very common, the following provides a method to format the time string for your reference

dateFormat(time,fmt,utc){ var theTime = DateTime.parse(time); if(utc){ theTime = theTime.toUtc(); } var o = {" M + ": theTime. The month + 1, / /" d + ": in theTime. Day, / / day" h + ": theTime. The hour," M + "/ / hour: Thetime. minute, // millisecond "s ": thetime. second, // millisecond "q ":(thetime. month + 3) / 3, // millisecond "s ": thetime. millisecond // millisecond}; RegExp exp = new RegExp("(y+)"); if (exp.hasMatch(fmt)) fmt = fmt.replaceAll(exp.stringMatch(fmt), theTime.year.toString().substring(4 - exp.stringMatch(fmt).length)); for (var k in o.keys){ RegExp expo = new RegExp("("+k+")"); if (expo.hasMatch(fmt)) fmt = fmt.replaceAll(expo.stringMatch(fmt), (expo.stringMatch(fmt).length == 1) ? (o[k]) : (("00" + o[k].toString()).substring(("" + o[k].toString()).length))); } try{ return fmt; }catch(e){ return ""; }}Copy the code

This is a common approach to dart time types.

The sample

  1. Calculate how many days apart the two dates are?
var startDate = new DateTime(2020, 12, 20);
var endDate = new DateTime.now();
var days = endDate.difference(startDate).inDays;
Copy the code
  1. Calculate how many hours apart the two dates are?
var startDate = new DateTime(2020, 12, 20);
var endDate = new DateTime.now();
var hours = endDate.difference(startDate).inHours;
Copy the code

And you can see how easy it is, if we just use the difference method, we can get the difference of all the time units.