How can we identify time section in datetime flutter - flutter

I will receive DateTime in UTC format from API and I need to convert the DateTime to local time zone based on the condition.
We have toLocal() method to change the time based on the device time zone.
condition: 23-4-2021 // no need to change it to toLocal()
23-4-2021 00:00:00 // no need to change it to toLocal()
23-4-2021 10:30:34 // need to change it to toLocal()
If we have time in the DateTime then only we have to change it in local time.
DateTime utcToDateTimeLocal(DateTime value) {
return value.toLocal();
}
Thanks!

Something like this maybe ?
DateTime utcToDateTimeLocal(DateTime value) {
if (value.hour!=0 || value.minute!=0 || value.second!=0){
return value.toLocal();
}
return value;
}

Here is quick solution that work for me.
You can get time (or any format) by DateFormat class
In your case
dateTime = '23-4-2021 10:30:34'
final format = DateFormat('HH:mm a');
final clockString = format.format(dateTime);
you will get // 10:30 AM

DateTime utcToDateTimeLocal(DateTime value) {
var dateFormat =
DateFormat("dd-mm-yyyy hh:mm a"); // you can change the format here
var utcDate =
dateFormat.format(DateTime.parse(value.toString())); // pass the UTC time here
var localDate = dateFormat.parse(utcDate, true).toLocal().toString();
return DateTime.parse(localDate);
}

Related

Invalid date format for validation flutter

I have a form, the date picker is supposed to validate and check whether the end date is later than the start date. But my coding got error which says
Invalid date format
09/01/2023`
Here is my validation code:
TextEditingController _sDate = TextEditingController();
TextEditingController _eDate = TextEditingController();
String? endDateValidator(value) {
DateTime eDate = DateTime.parse(_eDate.text);
DateTime sDate = DateTime.parse(_sDate.text);
eDate = DateFormat("yyyy-MM-dd").format(eDate);
if (_sDate != null && _eDate == null) {
return "select Both data";
}
if (_eDate == null) return "select end date";
if (_eDate != null) {
if(eDate.isBefore(sDate))
return "End date must be after start date";
}
return null;}
How do I fix this?
Your date format is not regular(yyyy-MM-dd) format, you need to use custom format to format it, so instead of this:
DateTime eDate = DateTime.parse(_eDate.text);
DateTime sDate = DateTime.parse(_sDate.text);
eDate = DateFormat("yyyy-MM-dd").format(eDate);
You can use intl package and do this::
DateTime eDate = DateFormat("dd/MM/yyyy").parse(_eDate.text);
also in line four of your code, format(eDate) return you a string, you can't pass it to eDate, because it is DateTime. Also you don't need this line at all.
There are two methods of formatting dates if we are working in Flutter:
1.- Add the intl package (https://pub.dev/packages/intl) and you can access to this functions:
DateTime now = DateTime.now();
String formattedDate = DateFormat.yMMMEd().format(now);
print(formattedDate);
Output:
Tue, Jan 25, 2022
2.- Using Custom Pattern
DateTime now = DateTime.now();
formattedDate = DateFormat('EEEE, MMM d, yyyy').format(now);
print(formattedDate);
Output:
Tuesday, Jan 25, 2022
For more information:
https://api.flutter.dev/flutter/intl/DateFormat-class.html
I hope it was useful for you.

How to get DateTime with zeroed time in Flutter

I'm new to Flutter and I'm trying to output the start of the current day in UTC format.
I use Flutter 3.3.7 and Dart SDK 2.18.4.
First, I take the current date.
DateTime dt = DateTime.now();
Next, I use extension for the DateTime class, which I implemented myself.
extension DateTimeFromTimeOfDay on DateTime {
DateTime appliedFromTimeOfDay(TimeOfDay timeOfDay) {
return DateTime(year, month, day, timeOfDay.hour, timeOfDay.minute);
}
}
It outputs the same date, only with the time that I pass it via TimeOfDay class(In this case 00:00).
dt = dt.appliedFromTimeOfDay(const TimeOfDay(hour: 0, minute: 0));
print(dt.toUtc()); //2022-11-08 21:00:00.000Z
But when I run this code, it outputs a date with a non-zero time.
I also tried adding the toUtc() method to the extension.
extension DateTimeFromTimeOfDay on DateTime {
DateTime appliedFromTimeOfDay(TimeOfDay timeOfDay) {
return DateTime(year, month, day, timeOfDay.hour, timeOfDay.minute).toUtc();
}
}
That didn't work either.
How can I get the DateTime in UTC format with zeroed time of day? For example,
2022-11-08 00:00:00.000Z
DateTime has a utc constructor that allows you to do this.
extension DateTimeFromTimeOfDay on DateTime {
DateTime appliedFromTimeOfDay(TimeOfDay timeOfDay) {
return DateTime.utc(year, month, day, timeOfDay.hour, timeOfDay.minute);
}
}
DateTime today = DateTime.now()
.appliedFromTimeOfDay(const TimeOfDay(hour: 0, minute: 0)); // output: 2022-11-09 00:00:00.000Z (note the Z which indicate UTC)
Try it with this extension method
extension DateTimeExtension on DateTime {
DateTime getDateOnly() {
return DateTime(this.year, this.month, this.day);
}
}

Dart Flutter adding weeks to a DateTime

Guys. I want to write a simple code to add X weeks to a chosen Date but I just can't figure out how. I always get a ton of errors. The function should basically return the chosen date plus "addedweeks" in the format "dd-MM-yyyy". Below is my last attempt. Thanks in advance!
import 'dart:math' as math;
String? addXWeeks(
DateTime? datum,
int? addedweeks,
) {
// add 2 weeks
DateTime date = datum.toLocal;
date = DateTime(date.year, date.month, date.day + (addedweeks*7));
}
this is very easy. DateTime has a method called add. You only need to add 7 days, because duration has not the propertie "weeks".
Here is a samle:
void main() {
// Current date
DateTime date = DateTime.now();
// Weeks you want to add
int weeksToAdd = 10;
print("Before: $date");
// Multiply 7 (days a week) with your week and set int to and int
date = date.add(Duration(days: (7 * weeksToAdd).toInt()));
print("After: $date");
// Format date
print("Format date: ${date.day}.${date.month}.${date.year}");
}
The output:
Before: 2022-10-06 13:23:16.342888
After: 2022-12-15 12:23:16.342888
Format date: 15.12.2022

How to get difference between 1 Timestamp and 1 dateTime in minute or day

using DateTime we can use the following to get the difference
DateTime myFirstDateTime = DateTime.now();
DateTime mySecondtDateTime = DateTime.now();
myFirstDateTime.difference(mySecondtDateTime).inMinutes // or inDay
the previous code is working as expected but how can I handle the same between Timestamp and DateTime ?
I used the following but it give wrong result and strange negative numbers like -5623
Timestamp myTimestamp = // here I get the value from my Firebase field
DateTime myDateTime = DateTime.now();
then I convert it `toDate()`
myDateTime.difference(myTimestamp.toDate()).inMinutes; //or inDay
//output strange value
How can I do it? Thanks
You might have to move the brackets as follows:
myDateTime.difference(myTimestamp.toDate()).inMinutes;
Try this one out
var myTimestamp = // here you get the value from your Firebase field
DateTime myDateTime = DateTime.now();
DateTime myFirebaseTime = DateTime.parse(myTimestamp.toDate().toString());
myDateTime.difference(myFirebaseTime).inDays;

Comparing only dates of DateTimes in Dart

I need to store and compare dates (without times) in my app, without caring about time zones.
I can see three solutions to this:
(date1.year == date2.year && date1.month == date2.month && date1.day == date2.day)
This is what I'm doing now, but it's horrible verbose.
date1.format("YYYYMMDD") == date2.format("YYYYMMDD")
This is still rather verbose (though not as bad), but just seems inefficient to me...
Create a new Date class myself, perhaps storing the date as a "YYYYMMDD" string, or number of days since Jan 1 1980. But this means re-implementing a whole bunch of complex logic like different month lengths, adding/subtracting and leap years.
Creating a new class also avoids an edge case I'm worried about, where adding Duration(days: 1) ends up with the same date due to daylight saving changes. But there are probably edge cases with this method I'm not thinking of...
Which is the best of these solutions, or is there an even better solution I haven't thought of?
Since I asked this, extension methods have been released in Dart. I would now implement option 1 as an extension method:
extension DateOnlyCompare on DateTime {
bool isSameDate(DateTime other) {
return year == other.year && month == other.month
&& day == other.day;
}
}
You can use compareTo:
var temp = DateTime.now().toUtc();
var d1 = DateTime.utc(temp.year,temp.month,temp.day);
var d2 = DateTime.utc(2018,10,25); //you can add today's date here
if(d2.compareTo(d1)==0){
print('true');
}else{
print('false');
}
DateTime dateTime = DateTime.now();
DateTime _pickedDate = // Some other DateTime instance
dateTime.difference(_pickedDate).inDays == 0 // <- this results to true or false
Because difference() method of DateTime return results as Duration() object, we can simply compare days only by converting Duration into days using inDays property
The easiest option is just to use DateUtils
For example
if (DateUtils.isSameDay(date1, date2){
print('same day')
}
isSameDay takes in 2 DateTime objects and ignores the time element
I am using this function to calculate the difference in days.
Comparing dates is tricky as the result depends not just on the timestamps but also the timezone of the user.
int diffInDays (DateTime date1, DateTime date2) {
return ((date1.difference(date2) - Duration(hours: date1.hour) + Duration(hours: date2.hour)).inHours / 24).round();
}
Use instead the package: dart_date
Dart Extensions for DartTime
dart_date provides the most comprehensive, yet simple and consistent toolset for manipulating Dart dates.
dart_date
DateTime now = DateTime.now();
DateTime date = ....;
if (date.isSameDay(now)) {
//....
} else {
//....
}
Also here the difference in days :
int differenceInDays(DateTime a, DateTime b) => a.differenceInDays(b);
Use isAtSameMomentAs:
var date1 = DateTime.now();
var date2 = date1.add(Duration(seconds: 1));
var isSame = date1.isAtSameMomentAs(date2); // false