I would like to compare last_uploaded_time with current time.
How to check whether the two time is more or less than one minute?
bool compareTime(String starts) {
print(starts);
var start = starts.split(":");
DateTime currentDateTime = DateTime.now();
String currentTime =
DateFormat(DateUtil.TIME_FORMAT).format(currentDateTime);
print(currentTime);
var end = currentTime.split(":");
DateTime initDateTime = DateTime(
currentDateTime.year, currentDateTime.month, currentDateTime.day);
var startDate = (initDateTime.add(Duration(hours: int.parse(start[0]))))
.add(Duration(minutes: int.parse(start[1])));
var endDate = (initDateTime.add(Duration(hours: int.parse(end[0]))))
.add(Duration(minutes: int.parse(end[1])));
if (currentDateTime.isBefore(endDate) &&
currentDateTime.isAfter(startDate)) {
print("CURRENT datetime is between START and END datetime");
return true;
} else {
print("NOT BETWEEN");
return false;
}
}
Output
I/flutter (12908): 01:16
I/flutter (12908): 01:40
I/flutter (12908): NOT BETWEEN
difference
not exactly working with minutes and seconds so you can use some custom algorithm like
import 'package:intl/intl.dart';
class IntelModel { static String timeSinceDate(DateTime date) {
final now = DateTime.now();
final difference = now.toLocal().difference(date.toLocal());
if ((now.day - date.day) >= 8) {
return 'A few weeks ago';
} else if ((now.day - date.day) >= 1) {
return '${(now.day - date.day)} days ago';
} else if (now.day == date.day) {
if (now.hour > date.hour) {
if ((now.hour - date.hour) >= 2) {
if (now.minute == date.minute) {
return '${(now.hour - date.hour)} hours ago';
} else {
var mins = now.minute - date.minute;
if (mins > 1) {
return '${(now.hour - date.hour)} h ${(now.minute - date.minute)} minutes ago';
} else {
return '${(now.hour - date.hour) - 1} h ${60 + mins} minutes ago';
}
}
} else if ((now.hour - date.hour) == 1) {
int timeMin = now.minute + (60 - date.minute);
if (timeMin == 60) {
return '1 hours ago';
} else if (timeMin >= 60) {
return '1 h ${timeMin - 60} mins ago';
} else {
return '$timeMin minutes ago';
}
}
} else if (now.hour == date.hour) {
if (now.minute > date.minute) {
return '${(now.minute - date.minute)} minutes ago';
} else if (date.minute == now.minute) {
return '${(now.second - date.second)} seconds ago';
}
}
} else {
return 'Error in time';
} } }
void main() {
String getDifference(DateTime date){
Duration duration = DateTime.now().difference(date);
String differenceInMinutes = (duration.inMinutes).toString();
return differenceInMinutes;
}
String str = getDifference(DateTime.parse('2021-09-24'));
print (str);
}
i tried above code on dartpad, you can use this to compare tow dateTime variables. As per above example, you can get more options to compare for eg duration.inDays,duration.inHours,duration.inSeconds etc.
Related
i got a chart that display months (in french) when i go below the month == 1, i would like to go back to my current month and not see my 'error'.
Is there a method to make it ?
String numericToStringMonth(int month) {
if (month < 1 || month > 12) {
return 'error';
} else if (month == 1) {
return 'Janvier';
} else if (month == 2) {
return 'Février';
} else if (month == 3) {
return 'Mars';
} else if (month == 4) {
return 'Avril';
} else if (month == 5) {
return 'Mai';
} else if (month == 6) {
return 'Juin';
} else if (month == 7) {
return 'Juillet';
} else if (month == 8) {
return 'Août';
} else if (month == 9) {
return 'Septembre';
} else if (month == 10) {
return 'Octobre';
} else if (month == 11) {
return 'Novembre';
} else if (month == 12) {
return 'Décembre';
} else {
return 'error';
}
}
String numericToStringMonth(int month) {
// make list of months for easier access
List<String> months = [
'Janvier',
'Février',
'Mars',
'Avril',
'Mai',
'Juin',
'Juillet',
'Août',
'Septembre',
'Octobre',
'Novembre',
'Décembre'
];
int currentMonth = month - 1;
try {
if (currentMonth > 11) {
throw Exception('Month must be between 1 and 12');
} else if (currentMonth < 0) {
// setting month to the first one when value goes below 0, add your logic here
currentMonth = 1;
}
return months[currentMonth];
} catch (e) {
print(e);
}
return '';
}
I am using the following class to translate texts depending on the device's locale:
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:yaml/yaml.dart';
class MovMapLocalizations {
final String localeName;
MovMapLocalizations(this.localeName);
static const LocalizationsDelegate<MovMapLocalizations> delegate =
_MovMapLocalizationsDelegate();
YamlMap translations;
Future load() async {
String yamlString = await rootBundle.loadString('lang/${localeName}.yml');
translations = loadYaml(yamlString);
}
String t(String key) {
try {
var keys = key.split(".");
dynamic translated = translations;
keys.forEach((k) => translated = translated[k]);
if (translated == null) {
return "Key not found: $key";
}
return translated;
} catch (e) {
return "Key not found: $key";
}
}
}
class _MovMapLocalizationsDelegate
extends LocalizationsDelegate<MovMapLocalizations> {
const _MovMapLocalizationsDelegate();
#override
bool isSupported(Locale locale) {
print("#########################LOCALE ACTUAL:"+locale.languageCode);
return ['es', 'en'].contains(locale.languageCode);
}
#override
Future<MovMapLocalizations> load(Locale locale) async {
var t = MovMapLocalizations(locale.languageCode);
await t.load();
return t;
}
#override
bool shouldReload(covariant LocalizationsDelegate<MovMapLocalizations> old) {
return false;
}
}
I have also two yaml files to declare the translations: en.yaml and es.yaml:
en.yaml
login:
email: Email
password: Password
login: Sign In
signup: Sign Up
or: Or
newHere: New Here?
signup:
email2: Email
password2: Password
login2: Sign In
signup2: Sign Up
or2: Or
alreadyAccount: Already Have an User Account?
muro:
expand: read more
collapse: close
delete: Delete
denunciar: Report
already: Has already been reported
has_denunciado: You have reported this post
time_ago:
yearsago: years ago
es.yaml
login:
email: Correo electrónico
password: Contraseña
login: Entrar
signup: Registrar
or: O
newHere: ¿Nuevo aquí?
signup:
email2: Correo electrónico
password2: Contraseña
login2: Entrar
signup2: Registrar
or2: O
alreadyAccount: ¿Ya tienes cuenta de usuario?
muro:
expand: leer más
collapse: cerrar
delete: Borrar
denunciar: Denunciar
already: Ya ha sido denunciado
has_denunciado: Has denunciado este post
time_ago:
yearsago: años
Then on every class where I need to make use of translations I am including:
MovMapLocalizations localizations =
Localizations.of<MovMapLocalizations>(context, MovMapLocalizations);
And later, to translate a given text I put the related translation as:
Text(localizations.t("muro.denunciar")
But now I need to implement the use of translations inside a separate class called which doesn't have a context to make use of:
MovMapLocalizations localizations =
Localizations.of<MovMapLocalizations>(context, MovMapLocalizations);
This is the class:
class TimeAgo{
String formatearFecha(Timestamp timestamp){
var dateFromTimeStamp =
DateTime.fromMillisecondsSinceEpoch(timestamp.seconds * 1000);
return DateFormat('dd-MM-yyyy HH:mm').format(dateFromTimeStamp);
}
String timeAgoSinceDate(String dateString, {bool numericDates = true}) {
DateTime date = DateTime.parse(dateString);
final date2 = DateTime.now();
final difference = date2.difference(date);
if ((difference.inDays / 365).floor() >= 2) {
return '${(difference.inDays / 365).floor()} years ago';
} else if ((difference.inDays / 365).floor() >= 1) {
return (numericDates) ? '1 year ago' : 'Last year';
} else if ((difference.inDays / 30).floor() >= 2) {
return '${(difference.inDays / 365).floor()} months ago';
} else if ((difference.inDays / 30).floor() >= 1) {
return (numericDates) ? '1 month ago' : 'Last month';
} else if ((difference.inDays / 7).floor() >= 2) {
return '${(difference.inDays / 7).floor()} weeks ago';
} else if ((difference.inDays / 7).floor() >= 1) {
return (numericDates) ? '1 week ago' : 'Last week';
} else if (difference.inDays >= 2) {
return '${difference.inDays} days ago';
} else if (difference.inDays >= 1) {
return (numericDates) ? '1 day ago' : 'Yesterday';
} else if (difference.inHours >= 2) {
return '${difference.inHours} hours ago';
} else if (difference.inHours >= 1) {
return (numericDates) ? '1 hour ago' : 'An hour ago';
} else if (difference.inMinutes >= 2) {
return '${difference.inMinutes} minutes ago';
} else if (difference.inMinutes >= 1) {
return (numericDates) ? '1 minute ago' : 'A minute ago';
} else if (difference.inSeconds >= 3) {
return '${difference.inSeconds} seconds ago';
} else {
return 'Just now';
}
}
}
What should I do to make it possible?
You can pass a top-level GlobalKey to MaterialApp's navigatorKey property.
Then you can get the current route's context by globalKey.currentContext.
https://api.flutter.dev/flutter/material/MaterialApp/navigatorKey.html
I have created a function that receives a String date and returns a string that shows the time between the given date and the current DateTime in the format: x days ago, x months ago, just now, x years ago, yesterday, etc:
This is the code for that function:
String tiempoDesdeFecha(String dateString, {bool numericDates = true}) {
DateTime date = DateTime.parse(dateString);
final date2 = DateTime.now();
final difference = date2.difference(date);
if ((difference.inDays / 365).floor() >= 2) {
return "hace".tr()+'${(difference.inDays / 365).floor()}'+"yearsago".tr();
} else if ((difference.inDays / 365).floor() >= 1 ) {
return (numericDates) ? '1yearago'.tr() : 'lastyear'.tr()+" "+(numericDates).toString();
} else if ((difference.inDays / 30).floor() >= 2) {
return "hace".tr()+'${(difference.inDays / 365).floor()}'+"monthsago".tr();
} else if ((difference.inDays / 30).floor() >= 1) {
return (numericDates) ? '1monthago'.tr() : 'lastmonth'.tr();
} else if ((difference.inDays / 7).floor() >= 2) {
return "hace".tr()+'${(difference.inDays / 7).floor()}'+ 'weeksago'.tr();
} else if ((difference.inDays / 7).floor() >= 1) {
return (numericDates) ? "1weekago".tr() : 'lastweek'.tr();
} else if (difference.inDays >= 2) {
return "hace".tr()+'${difference.inDays}'+ 'daysago'.tr();
} else if (difference.inDays >= 1) {
return (numericDates) ? '1dayago'.tr() : 'yesterday'.tr();
} else if (difference.inHours >= 2) {
return "hace".tr()+'${difference.inHours}'+ 'hoursago'.tr();
} else if (difference.inHours >= 1) {
return (numericDates) ? '1hourago'.tr() : 'anhourago'.tr();
} else if (difference.inMinutes >= 2) {
return "hace".tr()+'${difference.inMinutes} ' +'minutesago'.tr();
} else if (difference.inMinutes >= 1) {
return (numericDates) ? '1minuteago'.tr() : 'aminuteago'.tr();
} else if (difference.inSeconds >= 3) {
return "hace".tr()+'${difference.inSeconds}'+ 'secondsago'.tr();
} else {
return 'justnow'.tr();
}
}
I have included the code to show the returned string in one of the four Locale I am using.
Everything is working fine, but the condition:
else if ((difference.inDays / 30).floor() >= 2) {
return "hace".tr()+'${(difference.inDays / 365).floor()}'+"monthsago".tr();
which is always returning 0 months ago.
I am calling the function from:
fecha_recibida = DateFormat('yyyy-MM-dd HH:mm',"en").format(date);
fecha_recibida = tiempoDesdeFecha(fecha_recibida);
I am testing that issue with following String date:
"2021-5-5 19:34"
What am I doing wrong?
I believe the error is in the returned string,
difference.inDays / 365 must be difference.inDays / 30.
So the condition should look like..
else if ((difference.inDays / 30).floor() >= 2) {
return "hace".tr()+'${(difference.inDays / 30).floor()}'+"monthsago".tr();
A plus, as #aman mentioned, you could use timeago package
How do we convert specific time format ("yyyy-MM-dd-HH-mm-ss") to calculate time ago in Flutter? I have the codes below for my android app, however I am trying out Flutter which uses Dart. Can someone provide a pointer here on how we can achieve this?
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);
This is how I've implemented it:
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';
}
then for example, you can embed it inside of an object, and call it like this:
Text(viewmodel.post.timeAgoSinceDate())
I want to greet user when they visit my app
I have tried using TimeOfDay but it isn't working.
TimeOfDay now = TimeOfDay.now();
greetings(String greeting){
var greeting = now;
if(greeting <= '11: 59'){
return 'Morning';
} else if (greeting > '11:59' && <= '16:59'){
return 'Afternoon';
} else if (greeting > '16:59' && <= '23:59'){
return 'Afternoon';
} else {
return 'Morning';
}
}
Try using DateTime.now(), for example:
String greeting() {
var hour = DateTime.now().hour;
if (hour < 12) {
return 'Morning';
}
if (hour < 17) {
return 'Afternoon';
}
return 'Evening';
}
TimeOfDay.now().period;
// This will return DayPeriod.am or DayPeriod.pm, you can show the greeting message accordingly
Link: https://api.flutter.dev/flutter/material/TimeOfDay/period.html
import 'package:flutter/material.dart';
void main(){
TimeOfDay day = TimeOfDay.now();
switch(day.period){
case DayPeriod.am: print('its morning');
break;
case DayPeriod.pm: print('its evening/night');
}
}
You are using TimeOfDay in wrong way. Your code should work if you use it properly.
String greetings(){
final hour = TimeOfDay.now().hour;
if(hour <= 12){
return 'Morning';
} else if (hour <= 17){
return 'Afternoon';
}
return 'Evening';
}