datetime.dart 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import 'package:date_format/date_format.dart';
  2. import 'package:intl/intl.dart';
  3. abstract class DataTimeUtils {
  4. /// 转成UTC字符串
  5. static String convertToUTCString(DateTime date) {
  6. // final utcFormatter = DateFormat('yyyy-MM-ddTHH:mm:ssZ');
  7. // final utcString = utcFormatter.format(date.toUtc());
  8. // return utcString;
  9. return formatDate(date.toUtc(),
  10. [yyyy, '-', mm, '-', dd, 'T', HH, ':', nn, ':', ss, ' ', Z]);
  11. }
  12. static String formatDateString(DateTime date) {
  13. return formatDate(date, [yyyy, '-', mm, '-', dd]);
  14. }
  15. /// UTC字符串转DateTime
  16. static DateTime convertFromUTCString(String utcString) {
  17. final utcFormatter = DateFormat('yyyy-MM-ddTHH:mm:ssZ');
  18. final dateTime = utcFormatter.parseUtc(utcString);
  19. return dateTime;
  20. }
  21. static DateTime convertFromDateString(String utcString) {
  22. final utcFormatter = DateFormat('yyyy-MM-dd');
  23. final dateTime = utcFormatter.parseUtc(utcString);
  24. return dateTime;
  25. }
  26. /// 计算年龄
  27. static String calculateAge(DateTime birthDate) {
  28. DateTime currentDate = DateTime.now();
  29. int age = currentDate.year - birthDate.year;
  30. if (currentDate.month < birthDate.month ||
  31. (currentDate.month == birthDate.month &&
  32. currentDate.day < birthDate.day)) {
  33. age--;
  34. }
  35. return age.toString();
  36. }
  37. }