How to only change the time in DateTime? - flutter

I have a DateTime and I'm trying to do two things with it. 1: Only update the date and month. 2: Only update the time. How can I achieve that?
DateTime currentDateTime = DateTime.now();
void updateTime(DateTime newTime) {
currentDateTime = ?
}
void updateDate(DateTime newTime) {
currentDateTime = ?
}
Is there any way I can destruct the currentDateTime like DateTime(...currentDateTime, ..newTime)

Construct your Datetime object from Datetime.now() properties, instead of the whole Datetime.now() object. This should work.
DateTime currentDateTime = DateTime.now();
void updateTime(DateTime currentDateTime, DateTime newTime) {
currentDateTime = DateTime(
year: currentDateTime.year,
month: currentDateTime.month
day: currentDateTime.day,
hour: newTime.hour,
minute: newTime.minute,
second: newTime.second,
);
}
void updateDate(DateTime currentDateTime, DateTime newDate) {
currentDateTime = DateTime(
year: currentDateTime.year,
month: newTime.month
day: newTime.day,
hour: currentDateTime.hour,
minute: currentDateTime.minute,
second: currentDateTime.second,
);
}
Remember the constructor of Datetime looks like this
DateTime(int year, [int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0])

To only update time you can use TimeOfDay. This is approach that I can do
DateTime currentDateTime = DateTime.now();
void updateTime(TimeOfDay newTime) {
// 2020-09-07 09:03:24.469
TimeOfDay time = TimeOfDay(hour: newTime.hour, minute: newTime.minute);
currentDateTime = DateTime(currentDateTime.year, currentDateTime.month, currentDateTime.month, time.hour, time.minute);
// 2020-09-09 15:00:00.000
}
void updateDate(DateTime newTime) {
// 2020-09-09 15:00:00.000
currentDateTime = DateTime(newTime.year, newTime.month, newTime.day);
// 2021-01-01 00:00:00.000
}
I hope this is helpful.

Related

How to get the next near future value to the current time in a list in Flutter?

I have a store schedule that comes from the server. And I get the current time. I need to find the near future start_time to my current time in the list I am getting. For example, if the current time is 3:00 pm, I need to get the closest start_time, which is 5:00 pm. Tell me how to do it?
here I am accessing the key 'mon'
String dateFormat = DateFormat('EEE').format(timeNow).toLowerCase();
shopSchedule.templateFull![dateFormat]
You can do this to get closest time after now from your mon list:
String? selectedTime;
for (var element in mon) {
if (selectedTime == null) {
var now = DateTime.now();
DateTime tempDate = DateFormat("yyyy-MM-dd hh:mm").parse(
"${now.year}-${now.month}-${now.day} ${element["start_time"] as String}");
if (tempDate.isAfter(now)) {
selectedTime = element["start_time"];
}
} else {
var now = DateTime.now();
DateTime selectedDate = DateFormat("yyyy-MM-dd hh:mm")
.parse("${now.year}-${now.month}-${now.day} $selectedTime");
DateTime tempDate = DateFormat("yyyy-MM-dd hh:mm").parse(
"${now.year}-${now.month}-${now.day} ${element["start_time"] as String}");
if (tempDate.isBefore(selectedDate) && tempDate.isAfter(now)) {
selectedTime = element["start_time"];
}
}
}

How to get a list of each week in a time range with Dart?

I am trying to build a weeks-timeline in my Flutter app.
I am trying to generate a list of all of the weeks in a given time range (for example December 2020 - December 2021).
Each week will be a list by itself, which will hold the days. Something like this:
[
[
{
dayName: 'Sunday',
date: 'December 13 2020',
},
{
dayName: 'Monday',
date: 'December 14 2020',
},
{
dayName: 'Tuesday',
date: 'December 15 2020',
},
{
dayName: 'Wednesday',
date: 'December 16 2020',
},
{
dayName: 'Thursday',
date: 'December 17 2020',
},
{
dayName: 'Friday',
date: 'December 18 2020',
},
{
dayName: 'Saturday',
date: 'December 19 2020',
},
],
//Another Week Array
//Another Week Array
//Etc
]
Does anyone know how can I achieve this type of data in Dart and Flutter?
Thank you!
As Stefano wrote, it's good to create a class with a structure to be able to achieve your goals. My suggestion is a little more simple since I just wrote a method you could use. You could even create an extension on the DateTime class and use that in the future, or implement it in a static class, or add it to an instance class. Here is the complete example that works on DartPad:
void main() {
var weeks = getWeeksForRange(DateTime.utc(2020,08,12), DateTime.utc(2020,10,12));
print(weeks);
}
List<List<DateTime>> getWeeksForRange(DateTime start, DateTime end) {
var result = List<List<DateTime>>();
var date = start;
var week = List<DateTime>();
while(date.difference(end).inDays <= 0) {
// start new week on Monday
if (date.weekday == 1 && week.length > 0) {
print('Date $date is a Monday');
result.add(week);
week = List<DateTime>();
}
week.add(date);
date = date.add(const Duration(days: 1));
}
result.add(week);
return result;
}
This method can take any two dates and create a list of lists (weeks) of DateTime objects. Since in the result you will have many DateTime results, you can then map them however you want since they will have all information about its date, year, weekday and will keep the formatting feature.
One first step could be to create a Class according to your needs:
class Day {
final DateTime dateTime;
Day({
this.dateTime,
});
String get day => DateFormat('EEEE').format(dateTime);
String get date => DateFormat('yMMMd').format(dateTime);
Map<String, String> toMap() => {'dayName': day, 'date': date};
}
We can construct the Class above just with a DateTime and from it, we can derive the day and date using DateFormat in the getters:
String get day => DateFormat('EEEE').format(dateTime); // returns "Friday" for example
String get date => DateFormat('yMMMd').format(dateTime); // returns "Jun 13, 2021" for example
The toMap() method allows use to easily convert the Class to a Map<String, String>:
Map<String, String> toMap() => {'dayName': day, 'date': date};
We now need to store the Days in a List<Day>:
List<Day> days = [];
By iterating from the starting DateTime to the ending DateTime:
DateTime now = DateTime.now(); // as an example
DateTime start = now;
DateTime after = now.add(Duration(days: 180));
DateTime iterator = start;
List<Day> days = [];
while (iterator.isBefore(after)) {
days.add(Day(dateTime: iterator));
iterator = iterator.add(Duration(days: 1));
}
A full source code for the scenario outlined can be found below:
import 'package:intl/intl.dart';
class Day {
final DateTime dateTime;
Day({
this.dateTime,
});
String get day => DateFormat('EEEE').format(dateTime);
String get date => DateFormat('yMMMd').format(dateTime);
String toString() =>
'\t{\n\t\t"dayName": "$day",\n\t\t"date": "$date"\n\t}\n';
Map<String, String> toMap() => {'dayName': day, 'date': date};
}
void main() {
DateTime now = DateTime.now();
DateTime start = now;
DateTime after = now.add(Duration(days: 180));
DateTime iterator = start;
List<Day> days = [];
while (iterator.isBefore(after)) {
days.add(Day(dateTime: iterator));
iterator = iterator.add(Duration(days: 1));
}
print(days);
}
If you'd like to group the Days by week, we'll then need a multi-dimensional List:
void main() {
DateTime now = DateTime.now();
DateTime start = now;
DateTime after = now.add(Duration(days: 180));
DateTime iterator = start;
List<List<Day>> days = [[]]; // multi-dimensional List
int i = 0;
while (iterator.isBefore(after)) {
if (days[i].isEmpty) days.add([]); // init of the week List
days[i].add(Day(dateTime: iterator));
if (iterator.weekday == 7) i++; // new week
iterator = iterator.add(Duration(days: 1));
}
print(days);
}

How to check if current date and time falls between two given date and time in Flutter

I have the below info:
final startDateTime = DateTime(2020, 7, 6, 18, 00);
final endDateTime = DateTime(2020, 7, 7, 19, 00);
final currentDateTime = DateTime.now();
How do I find if currentDateTime is between startDateTime and endDateTime.
Define a method:
bool isCurrentDateInRange(DateTime startDate, DateTime endDate) {
final currentDate = DateTime.now();
return currentDate.isAfter(startDate) && currentDate.isBefore(endDate);
}
Use it like:
var isDateInRange = isCurrentDateInRange(startDate, endDate);
if (currentDateTime.isAfter(startDateTime) && currentDateTime.isBefore(endDateTime)) {
...
}

How can I get the difference between 2 times?

I'm working on a flutter app as a project and I'm stuck with how to get the difference between two times. The first one I'm getting is from firebase as a String, which I then format to a DateTime using this:DateTime.parse(snapshot.documents[i].data['from']) and it gives me 14:00 for example. Then, the second is DateTime.now().
I tried all methods difference, subtract, but nothing works!
Please help me to get the exact duration between those 2 times.
I need this for a Count Down Timer.
This is an overview of my code:
.......
class _ActualPositionState extends State<ActualPosition>
with TickerProviderStateMixin {
AnimationController controller;
bool hide = true;
var doc;
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inHours}:${duration.inMinutes % 60}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
#override
void initState() {
super.initState();
var d = Firestore.instance
.collection('users')
.document(widget.uid);
d.get().then((d) {
if (d.data['parking']) {
setState(() {
hide = false;
});
Firestore.instance
.collection('historyParks')
.where('idUser', isEqualTo: widget.uid)
.getDocuments()
.then((QuerySnapshot snapshot) {
if (snapshot.documents.length == 1) {
for (var i = 0; i < snapshot.documents.length; i++) {
if (snapshot.documents[i].data['date'] ==
DateFormat('EEE d MMM').format(DateTime.now())) {
setState(() {
doc = snapshot.documents[i].data;
});
Duration t = DateTime.parse(snapshot.documents[i].data['until'])
.difference(DateTime.parse(
DateFormat("H:m:s").format(DateTime.now())));
print(t);
}
}
}
});
}
});
controller = AnimationController(
duration: Duration(hours: 1, seconds: 10),
vsync: this,
);
controller.reverse(from: controller.value == 0.0 ? 1.0 : controller.value);
}
double screenHeight;
#override
Widget build(BuildContext context) {
screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
.............
you can find the difference between to times by using:
DateTime.now().difference(your_start_time_here);
something like this:
var startTime = DateTime(2020, 02, 20, 10, 30); // TODO: change this to your DateTime from firebase
var currentTime = DateTime.now();
var diff = currentTime.difference(startTime).inDays; // HINT: you can use .inDays, inHours, .inMinutes or .inSeconds according to your need.
example from DartPad:
void main() {
final startTime = DateTime(2020, 02, 20, 10, 30);
final currentTime = DateTime.now();
final diff_dy = currentTime.difference(startTime).inDays;
final diff_hr = currentTime.difference(startTime).inHours;
final diff_mn = currentTime.difference(startTime).inMinutes;
final diff_sc = currentTime.difference(startTime).inSeconds;
print(diff_dy);
print(diff_hr);
print(diff_mn);
print(diff_sc);
}
Output: 3,
77,
4639,
278381,
Hope this helped!!
You can use the DateTime class to find out the difference between two dates.
DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11');
DateTime dateTimeNow = DateTime.now();
final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');
final differenceInMonths = dateTimeNow.difference(dateTimeCreatedAt).inMonths;
print('$differenceInMonths');
Use this code:
var time1 = "14:00";
var time2 = "09:00";
Future<int> getDifference(String time1, String time2) async
{
DateFormat dateFormat = DateFormat("yyyy-MM-dd");
var _date = dateFormat.format(DateTime.now());
DateTime a = DateTime.parse('$_date $time1:00');
DateTime b = DateTime.parse('$_date $time2:00');
print('a $a');
print('b $a');
print("${b.difference(a).inHours}");
print("${b.difference(a).inMinutes}");
print("${b.difference(a).inSeconds}");
return b.difference(a).inHours;
}
To compute a difference between two times, you need two DateTime objects. If you have times without dates, you will need to pick a date. Note that this is important because the difference between two times can depend on the date if you're using a local timezone that observes Daylight Saving Time.
If your goal is to show how long it will be from now to the next specified time in the local timezone:
import 'package:intl/intl.dart';
/// Returns the [Duration] from the current time to the next occurrence of the
/// specified time.
///
/// Always returns a non-negative [Duration].
Duration timeToNext(int hour, int minute, int second) {
var now = DateTime.now();
var nextTime = DateTime(now.year, now.month, now.day, hour, minute, second);
// If the time precedes the current time, treat it as a time for tomorrow.
if (nextTime.isBefore(now)) {
// Note that this is not the same as `nextTime.add(Duration(days: 1))` across
// DST changes.
nextTime = DateTime(now.year, now.month, now.day + 1, hour, minute, second);
}
return nextTime.difference(now);
}
void main() {
var timeString = '14:00';
// Format for a 24-hour time. See the [DateFormat] documentation for other
// format specifiers.
var timeFormat = DateFormat('HH:mm');
// Parsing the time as a UTC time is important in case the specified time
// isn't valid for the local timezone on [DateFormat]'s default date.
var time = timeFormat.parse(timeString, true);
print(timeToNext(time.hour, time.minute, time.second));
}
You can use this approch
getTime(time) {
if (!DateTime.now().difference(time).isNegative) {
if (DateTime.now().difference(time).inMinutes < 1) {
return "a few seconds ago";
} else if (DateTime.now().difference(time).inMinutes < 60) {
return "${DateTime.now().difference(time).inMinutes} minutes ago";
} else if (DateTime.now().difference(time).inMinutes < 1440) {
return "${DateTime.now().difference(time).inHours} hours ago";
} else if (DateTime.now().difference(time).inMinutes > 1440) {
return "${DateTime.now().difference(time).inDays} days ago";
}
}
}
And You can call it getTime(time) Where time is DateTime Object.

Add/Subtract months/years to date in dart?

I saw that in dart there is a class Duration but it cant be used add/subtract years or month. How did you managed this issue, I need to subtract 6 months from an date. Is there something like moment.js for dart or something around?
Thank you
Okay so you can do that in two steps, taken from #zoechi (a big contributor to Flutter):
Define the base time, let us say:
var date = new DateTime(2018, 1, 13);
Now, you want the new date:
var newDate = new DateTime(date.year, date.month - 1, date.day);
And you will get
2017-12-13
You can use the subtract and add methods
date1.subtract(Duration(days: 7, hours: 3, minutes: 43, seconds: 56));
date1.add(Duration(days: 1, hours: 23)));
Flutter Docs:
Subtract
Add
Try out this package, Jiffy. Adds and subtracts date time with respect to how many days there are in a month and also leap years. It follows the simple syntax of momentjs
You can add and subtract using the following units
years, months, weeks, days, hours, minutes, seconds and milliseconds
To add 6 months
DateTime d = Jiffy().add(months: 6).dateTime; // 2020-04-26 10:05:57.469367
// You can also add you own Datetime object
DateTime d = Jiffy(DateTime(2018, 1, 13)).add(months: 6).dateTime; // 2018-07-13 00:00:00.000
You can also do chaining using dart method cascading
var jiffy = Jiffy().add(months: 5, years: 1);
DateTime d = jiffy.dateTime; // 2021-03-26 10:07:10.316874
// you can also format with ease
String s = jiffy.format("yyyy, MMM"); // 2021, Mar
// or default formats
String s = jiffy.yMMMMEEEEdjm; // Friday, March 26, 2021 10:08 AM
You can use subtract and add methods
Subtract
Add
But you have to reassign the result to the variable, which means:
This wouldn't work
date1.add(Duration(days: 1, hours: 23)));
But this will:
date1 = date1.add(Duration(days: 1, hours: 23)));
For example:
void main() {
var d = DateTime.utc(2020, 05, 27, 0, 0, 0);
d.add(Duration(days: 1, hours: 23));
// the prev line has no effect on the value of d
print(d); // prints: 2020-05-27 00:00:00.000Z
//But
d = d.add(Duration(days: 1, hours: 23));
print(d); // prints: 2020-05-28 23:00:00.000Z
}
Dartpad link
In simple way without using any lib you can add Month and Year
var date = new DateTime(2021, 1, 29);
Adding Month :-
date = DateTime(date.year, date.month + 1, date.day);
Adding Year :-
date = DateTime(date.year + 1, date.month, date.day);
Not so simple.
final date = DateTime(2017, 1, 1);
final today = date.add(const Duration(days: 1451));
This results in 2020-12-21 23:00:00.000 because Dart considers daylight to calculate dates (so my 1451 days is missing 1 hour, and this is VERY dangerous (for example: Brazil abolished daylight savings in 2019, but if the app was written before that, the result will be forever wrong, same goes if the daylight savings is reintroduced in the future)).
To ignore the dayligh calculations, do this:
final date = DateTime(2017, 1, 1);
final today = DateTime(date.year, date.month, date.day + 1451);
Yep. Day is 1451 and this is OK. The today variable now shows the correct date and time: 2020-12-12 00:00:00.000.
It's pretty straightforward.
Simply add or subtract with numbers on DateTime parameters based on your requirements.
For example -
~ Here I had a requirement of getting the date-time exactly 16 years before today even with milliseconds and in the below way I got my solution.
DateTime today = DateTime.now();
debugPrint("Today's date is: $today"); //Today's date is: 2022-03-17 09:08:33.891843
After desired subtraction;
DateTime desiredDate = DateTime(
today.year - 16,
today.month,
today.day,
today.hour,
today.minute,
today.second,
today.millisecond,
today.microsecond,
);
debugPrint("16 years ago date is: $desiredDate"); // 16 years before date is: 2006-03-17 09:08:33.891843
Increase and Decrease of the day/month/year can be done by DateTime class
Initialise DateFormat which needed to be shown
var _inputFormat = DateFormat('EE, d MMM yyyy');
var _selectedDate = DateTime.now();
Increase Day/month/year:
_selectedDate = DateTime(_selectedDate.year,
_selectedDate.month + 1, _selectedDate.day);
Increase Day/month/year:
_selectedDate = DateTime(_selectedDate.year,
_selectedDate.month - 1, _selectedDate.day);
Above example is for only month, similar way we can increase or decrease year and day.
Can subtract any count of months.
DateTime subtractMonths(int count) {
var y = count ~/ 12;
var m = count - y * 12;
if (m > month) {
y += 1;
m = month - m;
}
return DateTime(year - y, month - m, day);
}
Also works
DateTime(date.year, date.month + (-120), date.day);
Future<void> main() async {
final DateTime now = DateTime.now();
var kdate = KDate.buildWith(now);
log("YEAR", kdate.year);
log("MONTH", kdate.month);
log("DATE", kdate.date);
log("Last Year", kdate.lastYear);
log("Last Month", kdate.lastMonth);
log("Yesturday", kdate.yesturday);
log("Last Week Date", kdate.lastWeekDate);
}
void log(title, data) {
print("\n$title ====> $data");
}
class KDate {
KDate({
this.now,
required this.year,
required this.month,
required this.date,
required this.lastYear,
required this.lastMonth,
required this.yesturday,
required this.lastWeekDate,
});
final DateTime? now;
final String? year;
final String? month;
final String? date;
final String? lastMonth;
final String? lastYear;
final String? yesturday;
final String? lastWeekDate;
factory KDate.buildWith(DateTime now) => KDate(
now: now,
year: (now.year).toString().split(" ")[0],
month: (now.month).toString().split(" ")[0],
date: (now.day).toString().split(" ")[0],
lastYear: (now.year - 1).toString().split(" ")[0],
lastMonth: DateTime(now.year, now.month, now.month)
.subtract(Duration(days: 28))
.toString()
.split(" ")[0]
.toString()
.split("-")[1],
yesturday: DateTime(now.year, now.month, now.day)
.subtract(Duration(days: 1))
.toString()
.split(" ")[0]
.toString()
.split("-")
.last,
lastWeekDate: DateTime(now.year, now.month, now.day)
.subtract(Duration(days: 7))
.toString()
.split(" ")[0]
.toString()
.split("-")
.last,
);
}
I'm a fan of using extensions in dart, and we can use them here like this:
extension DateHelpers on DateTime {
DateTime copyWith({
int? year,
int? month,
int? day,
int? hour,
int? second,
int? millisecond,
int? microsecond,
}) {
return DateTime(
year ?? this.year,
month ?? this.month,
day ?? this.day,
hour ?? this.hour,
second ?? this.second,
millisecond ?? this.millisecond,
microsecond ?? this.microsecond,
);
}
DateTime addYears(int years) {
return copyWith(year: this.year + years);
}
DateTime addMonths(int months) {
return copyWith(month: this.month + months);
}
DateTime addWeeks(int weeks) {
return copyWith(day: this.day + weeks*7);
}
DateTime addDays(int days) {
return copyWith(day: this.day + days);
}
}
You can then use this utility code as follows:
final now = DateTime.now();
final tomorrow = now.addDays(1);
final nextWeek = now.addWeeks(1);
final nextMonth = now.addMonths(1);
final nextYear = now.addYears(1);