gpt4 book ai didi

flutter - 特定时间格式的时间前

转载 作者:行者123 更新时间:2023-12-03 04:45:40 25 4
gpt4 key购买 nike

我们如何转换特定的时间格式(“yyyy-MM-dd-HH-mm-ss”)以计算Flutter之前的时间?我的Android应用程序具有以下代码,但是我正在尝试使用Dart的Flutter。有人可以在这里提供有关如何实现此目标的指示吗?

Date currentDate = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", locale);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dd = sdf.format(newsDate);
Date gmt = null;
try {
gmt = sdf.parse(dd);
} catch (ParseException e) {
e.printStackTrace();
}

long duration = currentDate.getTime() - gmt.getTime();

long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);

最佳答案

这是我的实现方式:

String timeAgoSinceDate({bool numericDates = true}) {
DateTime date = this.createdTime.toLocal();
final date2 = DateTime.now().toLocal();
final difference = date2.difference(date);

if (difference.inSeconds < 5) {
return 'Just now';
} else if (difference.inSeconds <= 60) {
return '${difference.inSeconds} seconds ago';
} else if (difference.inMinutes <= 1) {
return (numericDates) ? '1 minute ago' : 'A minute ago';
} else if (difference.inMinutes <= 60) {
return '${difference.inMinutes} minutes ago';
} else if (difference.inHours <= 1) {
return (numericDates) ? '1 hour ago' : 'An hour ago';
} else if (difference.inHours <= 60) {
return '${difference.inHours} hours ago';
} else if (difference.inDays <= 1) {
return (numericDates) ? '1 day ago' : 'Yesterday';
} else if (difference.inDays <= 6) {
return '${difference.inDays} days ago';
} else if ((difference.inDays / 7).ceil() <= 1) {
return (numericDates) ? '1 week ago' : 'Last week';
} else if ((difference.inDays / 7).ceil() <= 4) {
return '${(difference.inDays / 7).ceil()} weeks ago';
} else if ((difference.inDays / 30).ceil() <= 1) {
return (numericDates) ? '1 month ago' : 'Last month';
} else if ((difference.inDays / 30).ceil() <= 30) {
return '${(difference.inDays / 30).ceil()} months ago';
} else if ((difference.inDays / 365).ceil() <= 1) {
return (numericDates) ? '1 year ago' : 'Last year';
}
return '${(difference.inDays / 365).floor()} years ago';
}
然后,例如,您可以将其嵌入对象内部,并按如下方式调用它:
Text(viewmodel.post.timeAgoSinceDate())

关于flutter - 特定时间格式的时间前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62369728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com