How to get DateTime with zeroed time in Flutter - 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);
}
}

Related

hello i need to compare 2 dates like start date and end date and if i select a wednesday i need all wednesdays occuring between these dates

I have a scenario where user selects a start date and end date and user also selects a specific day I need to show that specific day with date that occurs between them.
I tried the Intl package difference method but did not work
You can use this method. Takes the start and end date and also the weekday. Note, can pass in 3 as an int or 'DateTime.wednesday' as the argument.
Note, idea based on mirkancal's answer in this thread
List<DateTime> getAllDatesOfAWeekday(
{required DateTime startDate,
required DateTime endDate,
required int weekday}) {
List<DateTime> allDates = [];
for (int i = 0; i <= endDate.difference(startDate).inDays; i++) {
if (startDate.add(Duration(days: i)).weekday == weekday) {
allDates.add(startDate.add(Duration(days: i)));
}
}
return allDates;
}

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 can we identify time section in datetime 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);
}

Getting just the year, month, and date in flutter? [duplicate]

All I can see in the documentation is DateTime.now() but it returns the Timespan also, and I need just the date.
Create a new date from now with only the parts you need:
DateTime now = new DateTime.now();
DateTime date = new DateTime(now.year, now.month, now.day);
Hint: "new" is optional in Dart since quite a while
If you want only the date without the timestamp. You can take the help of intl package.
main() {
var now = new DateTime.now();
var formatter = new DateFormat('yyyy-MM-dd');
String formattedDate = formatter.format(now);
print(formattedDate); // 2016-01-25
}
This requires the intl package:
dependencies:
intl: ^0.16.1
And finally import:
import 'package:intl/intl.dart';
You can get the current date using the DateTime class and format the Date using the DateFormat. The DateFormat class requires you to import the intl package so
add to pubspec.yaml
dependencies:
intl: ^0.17.0
and import
import 'package:intl/intl.dart';
and then format using
final now = new DateTime.now();
String formatter = DateFormat('yMd').format(now);// 28/03/2020
In case you are wondering How do you remember the date format(DateFormat('yMd'))? Then Flutter Docs is the answer
The DateFormat class allows the user to choose from a set of standard date time formats as well as specify a customized pattern under certain locales.
The below formats are taken directly from the docs
/// Examples Using the US Locale:
/// Pattern Result
/// ---------------- -------
new DateFormat.yMd() -> 7/10/1996
new DateFormat('yMd') -> 7/10/1996
new DateFormat.yMMMMd('en_US') -> July 10, 1996
new DateFormat.jm() -> 5:08 PM
new DateFormat.yMd().add_jm() -> 7/10/1996 5:08 PM
new DateFormat.Hm() -> 17:08 // force 24 hour time
ICU Name Skeleton
-------- --------
DAY d
ABBR_WEEKDAY E
WEEKDAY EEEE
ABBR_STANDALONE_MONTH LLL
STANDALONE_MONTH LLLL
NUM_MONTH M
NUM_MONTH_DAY Md
NUM_MONTH_WEEKDAY_DAY MEd
ABBR_MONTH MMM
ABBR_MONTH_DAY MMMd
ABBR_MONTH_WEEKDAY_DAY MMMEd
MONTH MMMM
MONTH_DAY MMMMd
MONTH_WEEKDAY_DAY MMMMEEEEd
ABBR_QUARTER QQQ
QUARTER QQQQ
YEAR y
YEAR_NUM_MONTH yM
YEAR_NUM_MONTH_DAY yMd
YEAR_NUM_MONTH_WEEKDAY_DAY yMEd
YEAR_ABBR_MONTH yMMM
YEAR_ABBR_MONTH_DAY yMMMd
YEAR_ABBR_MONTH_WEEKDAY_DAY yMMMEd
YEAR_MONTH yMMMM
YEAR_MONTH_DAY yMMMMd
YEAR_MONTH_WEEKDAY_DAY yMMMMEEEEd
YEAR_ABBR_QUARTER yQQQ
YEAR_QUARTER yQQQQ
HOUR24 H
HOUR24_MINUTE Hm
HOUR24_MINUTE_SECOND Hms
HOUR j
HOUR_MINUTE jm
HOUR_MINUTE_SECOND jms
HOUR_MINUTE_GENERIC_TZ jmv
HOUR_MINUTE_TZ jmz
HOUR_GENERIC_TZ jv
HOUR_TZ jz
MINUTE m
MINUTE_SECOND ms
SECOND s
Hope this helps you to get Date in any format.
this without using any package (it will convert to string)
DateTime dateToday =new DateTime.now();
String date = dateToday.toString().substring(0,10);
print(date); // 2021-06-24
With dart extension
extension MyDateExtension on DateTime {
DateTime getDateOnly(){
return DateTime(this.year, this.month, this.day);
}
}
Usage:
DateTime now = DateTime.now(); // 30/09/2021 15:54:30
DateTime dateOnly = now.getDateOnly(); // 30/09/2021
use this
import 'package:intl/intl.dart';
getCurrentDate() {
return DateFormat('yyyy-MM-dd – kk:mm').format(DateTime.now());
}
If you just need to print the year from a Timespan you can simply do:
DateTime nowDate = DateTime.now();
int currYear = nowDate.year;
print(currYear.toString());
There's no class in the core libraries to model a date w/o time. You have to use new DateTime.now().
Be aware that the date depends on the timezone: 2016-01-20 02:00:00 in Paris is the same instant as 2016-01-19 17:00:00 in Seattle but the day is not the same.
If you prefer a more concise and single line format, based on Günter Zöchbauer's answer, you can also write:
DateTime dateToday = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day) ;
Though, it'll make 3 calls to DateTime.now(), the extra variable won't be required, especially if using with Dart ternary operator or inside Flutter UI code block.
In case someone need the simplest way to format date/time in flutter, no plugin needed:
var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
String formattedDateTime() {
DateTime now = new DateTime.now();
return now.day.toString()+" "+MONTHS[now.month-1]+" "+now.year.toString()+" "+now.hour.toString()+":"+now.minute.toString()+":"+now.second.toString();
}
example result: 1 Jan 2020 07:30:45
Change:
MONTHS array to show the month in any language
the return string as needed: to show date only, time only, or date in
different format (dd/mm/yyyy, dd-mm-yyyy, mm/dd/yyyy, etc.)
If you want device's current date just use this
DateTime internetTime = DateTime.now();
DateTime date = new DateTime(now.year, now.month, now.day);
Or if u want internet time, then use below plugin
ntp: ^2.0.0
import 'package:ntp/ntp.dart';
final int offset = await NTP.getNtpOffset(
localTime: DateTime.now(), lookUpAddress: "time.google.com");
DateTime internetTime = DateTime.now().add(Duration(milliseconds: offset));
DateTime internetTime = new DateTime(now.year, now.month, now.day);
Or if you need internet time but you don't want to use plugin then use api call
"http://worldtimeapi.org/api/timezone/Asia/Kolkata"
{
"abbreviation": "IST",
"client_ip": "136.232.222.86",
"datetime": "2022-09-30T17:13:10.299478+05:30",
"day_of_week": 5,
"day_of_year": 273,
"dst": false,
"dst_from": null,
"dst_offset": 0,
"dst_until": null,
"raw_offset": 19800,
"timezone": "Asia/Kolkata",
"unixtime": 1664538190,
"utc_datetime": "2022-09-30T11:43:10.299478+00:00",
"utc_offset": "+05:30",
"week_number": 39
}
first go to pub.dev and get the intl package and add it to your project.
DateFormat.yMMMMd().format(the date you want to render . but must have the type DateTime)
You can use the day in DateTime.now()

How can I get the current date (w/o hour and minutes)?

All I can see in the documentation is DateTime.now() but it returns the Timespan also, and I need just the date.
Create a new date from now with only the parts you need:
DateTime now = new DateTime.now();
DateTime date = new DateTime(now.year, now.month, now.day);
Hint: "new" is optional in Dart since quite a while
If you want only the date without the timestamp. You can take the help of intl package.
main() {
var now = new DateTime.now();
var formatter = new DateFormat('yyyy-MM-dd');
String formattedDate = formatter.format(now);
print(formattedDate); // 2016-01-25
}
This requires the intl package:
dependencies:
intl: ^0.16.1
And finally import:
import 'package:intl/intl.dart';
You can get the current date using the DateTime class and format the Date using the DateFormat. The DateFormat class requires you to import the intl package so
add to pubspec.yaml
dependencies:
intl: ^0.17.0
and import
import 'package:intl/intl.dart';
and then format using
final now = new DateTime.now();
String formatter = DateFormat('yMd').format(now);// 28/03/2020
In case you are wondering How do you remember the date format(DateFormat('yMd'))? Then Flutter Docs is the answer
The DateFormat class allows the user to choose from a set of standard date time formats as well as specify a customized pattern under certain locales.
The below formats are taken directly from the docs
/// Examples Using the US Locale:
/// Pattern Result
/// ---------------- -------
new DateFormat.yMd() -> 7/10/1996
new DateFormat('yMd') -> 7/10/1996
new DateFormat.yMMMMd('en_US') -> July 10, 1996
new DateFormat.jm() -> 5:08 PM
new DateFormat.yMd().add_jm() -> 7/10/1996 5:08 PM
new DateFormat.Hm() -> 17:08 // force 24 hour time
ICU Name Skeleton
-------- --------
DAY d
ABBR_WEEKDAY E
WEEKDAY EEEE
ABBR_STANDALONE_MONTH LLL
STANDALONE_MONTH LLLL
NUM_MONTH M
NUM_MONTH_DAY Md
NUM_MONTH_WEEKDAY_DAY MEd
ABBR_MONTH MMM
ABBR_MONTH_DAY MMMd
ABBR_MONTH_WEEKDAY_DAY MMMEd
MONTH MMMM
MONTH_DAY MMMMd
MONTH_WEEKDAY_DAY MMMMEEEEd
ABBR_QUARTER QQQ
QUARTER QQQQ
YEAR y
YEAR_NUM_MONTH yM
YEAR_NUM_MONTH_DAY yMd
YEAR_NUM_MONTH_WEEKDAY_DAY yMEd
YEAR_ABBR_MONTH yMMM
YEAR_ABBR_MONTH_DAY yMMMd
YEAR_ABBR_MONTH_WEEKDAY_DAY yMMMEd
YEAR_MONTH yMMMM
YEAR_MONTH_DAY yMMMMd
YEAR_MONTH_WEEKDAY_DAY yMMMMEEEEd
YEAR_ABBR_QUARTER yQQQ
YEAR_QUARTER yQQQQ
HOUR24 H
HOUR24_MINUTE Hm
HOUR24_MINUTE_SECOND Hms
HOUR j
HOUR_MINUTE jm
HOUR_MINUTE_SECOND jms
HOUR_MINUTE_GENERIC_TZ jmv
HOUR_MINUTE_TZ jmz
HOUR_GENERIC_TZ jv
HOUR_TZ jz
MINUTE m
MINUTE_SECOND ms
SECOND s
Hope this helps you to get Date in any format.
this without using any package (it will convert to string)
DateTime dateToday =new DateTime.now();
String date = dateToday.toString().substring(0,10);
print(date); // 2021-06-24
With dart extension
extension MyDateExtension on DateTime {
DateTime getDateOnly(){
return DateTime(this.year, this.month, this.day);
}
}
Usage:
DateTime now = DateTime.now(); // 30/09/2021 15:54:30
DateTime dateOnly = now.getDateOnly(); // 30/09/2021
use this
import 'package:intl/intl.dart';
getCurrentDate() {
return DateFormat('yyyy-MM-dd – kk:mm').format(DateTime.now());
}
If you just need to print the year from a Timespan you can simply do:
DateTime nowDate = DateTime.now();
int currYear = nowDate.year;
print(currYear.toString());
There's no class in the core libraries to model a date w/o time. You have to use new DateTime.now().
Be aware that the date depends on the timezone: 2016-01-20 02:00:00 in Paris is the same instant as 2016-01-19 17:00:00 in Seattle but the day is not the same.
If you prefer a more concise and single line format, based on Günter Zöchbauer's answer, you can also write:
DateTime dateToday = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day) ;
Though, it'll make 3 calls to DateTime.now(), the extra variable won't be required, especially if using with Dart ternary operator or inside Flutter UI code block.
In case someone need the simplest way to format date/time in flutter, no plugin needed:
var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
String formattedDateTime() {
DateTime now = new DateTime.now();
return now.day.toString()+" "+MONTHS[now.month-1]+" "+now.year.toString()+" "+now.hour.toString()+":"+now.minute.toString()+":"+now.second.toString();
}
example result: 1 Jan 2020 07:30:45
Change:
MONTHS array to show the month in any language
the return string as needed: to show date only, time only, or date in
different format (dd/mm/yyyy, dd-mm-yyyy, mm/dd/yyyy, etc.)
If you want device's current date just use this
DateTime internetTime = DateTime.now();
DateTime date = new DateTime(now.year, now.month, now.day);
Or if u want internet time, then use below plugin
ntp: ^2.0.0
import 'package:ntp/ntp.dart';
final int offset = await NTP.getNtpOffset(
localTime: DateTime.now(), lookUpAddress: "time.google.com");
DateTime internetTime = DateTime.now().add(Duration(milliseconds: offset));
DateTime internetTime = new DateTime(now.year, now.month, now.day);
Or if you need internet time but you don't want to use plugin then use api call
"http://worldtimeapi.org/api/timezone/Asia/Kolkata"
{
"abbreviation": "IST",
"client_ip": "136.232.222.86",
"datetime": "2022-09-30T17:13:10.299478+05:30",
"day_of_week": 5,
"day_of_year": 273,
"dst": false,
"dst_from": null,
"dst_offset": 0,
"dst_until": null,
"raw_offset": 19800,
"timezone": "Asia/Kolkata",
"unixtime": 1664538190,
"utc_datetime": "2022-09-30T11:43:10.299478+00:00",
"utc_offset": "+05:30",
"week_number": 39
}
first go to pub.dev and get the intl package and add it to your project.
DateFormat.yMMMMd().format(the date you want to render . but must have the type DateTime)
You can use the day in DateTime.now()