6

Flutter&Dart日期格式化及时间戳转换

 2 years ago
source link: https://feizhaojun.com/?p=3472
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Flutter&Dart日期格式化及时间戳转换

分类: Flutter&Dart, 编程语言作者: mukti  时间: 2022-03-08 17:32:45 (星期二)

获取当前时间

Dart 获取当前时间,以及获取当前年、月、日等。

DateTime currentTime = DateTime.now();

currentTime.year // 当前年
currentTime.month // 当前月
currentTime.day // 当前日
currentTime.hour // 当前时
currentTime.minute // 当前分
currentTime.second // 当前秒
currentTime.millisecond // 当前毫秒
currentTime.microsecond // 当前微秒

currentTime.millisecondsSinceEpoch // 当前13位毫秒时间戳
currentTime.microsecondsSinceEpoch // 当前16位微秒数

currentTime.timeZoneName // 本地时区简码:GMT
currentTime.timeZoneOffset // 返回UTC与本地时差

创建指定时间

// 参数顺序依次是年月日时分秒
DateTime time = new DateTime(2022, 3, 22, 12, 33, 55);

创建指定时间还可以直接从符合日期格式的字符串直接转换,如下。

日期字符串转为时间
// 如果没有分、秒、毫秒,程序会自动补0
DateTime.parse('2022-03-08');
DateTime.parse('2022-03-08 17');
DateTime.parse('2022-03-08 17:01:22.789');
// 加上时区
DateTime.parse('2022-03-08 17:01:22+0800');
日期时间转成时间戳
DateTime currentTime = DateTime.now();

currentTime.millisecondsSinceEpoch // 当前13位毫秒时间戳
currentTime.microsecondsSinceEpoch // 当前16位微秒数
时间戳转日期时间
int time = 1646728287921;
DateTime.fromMillisecondsSinceEpoch(time);
// 比较两个时间的间隔,使用 difference() 和 Duration()

// difference() 可以计算两个时间差
time1.difference(time2) > Duration(year: 1, hours: 1, seconds: 1);

Duration diff = time1.difference(time2)
diff.inDays
diff.inHours
diff.inMinutes

// Duration() 是一个时间段长度
Duration timeDuration = new Duration(days: 1, minutes: 34);

// 时间先后比较
time1.isAtSameMomentAs(time2) // 时间相等,返回 true
time1.isBefore(time2) // time1 早,返回 true
time1.isAfter(time2) // time1 晚,返回 true
time1.compareTo(time2) // time1 晚,返回 1;time1 晚,返回 -1

可以给某个时间增加或减少时间段(Duration)。

DateTime time = DateTime.now();
time.add(new Duration(days: 5)); // 时间增加
time.add(new Duration(days: -5)); // 时间减少

领支付宝红包:打开支付宝搜索 726845401

领饿了么红包:0fυィ直文本 e:/$XGzEgR8$~.👉饿了么App👈【快來領外賣紅包,最高20元,人人都有哦~】

您的赞助将会鼓励作者技术文章创作以及支持本站运维。

Follow any responses to this post with its comments RSS feed. You can post a comment or trackback from your blog.
Your email is never published nor shared. Required fields are marked *
Name *
Email *
Website
评论

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK