How to subtract 1 day from current date time in dart? - flutter

I have a current datetime with followint function :
String cdate = DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now());
Now I want to subtract 1 day or 24 hours from this current date time.
How can i do that?

Don't manipulate the string, manipulate the date. From docs, adapted:
final now = DateTime.now();
final yesterday = now.subtract(const Duration(days: 1));
Apply the formatting just before you need to display the date, not before.

Date manipulation methods are provided by the DateTime class. Refer to DateTime documentation. Checkout now, add, subtract.
The following code shows how you can achieve what you want:
DateTime today = DateTime.now();
String cdate = DateFormat("yyyy-MM-dd HH:mm:ss").format(today);
DateTime yesterday = today.subtract(Duration(days: 1));
String ydate = DateFormat("yyyy-MM-dd HH:mm:ss").format(yesterday);

Try below code also refer add and subtract for DateTime
void main() {
var date = new DateTime.now();
date = DateTime(date.year, date.month, date.day - 1);
// or use subtract method also like below
//final day= date.subtract(Duration(days: 1));
print(date);
print(day);
}
Result using day-1:
2022-09-13 00:00:00.000
Result using subtract method :
2022-09-13 12:52:45.734

final currentDay = DateTime.now();
final yesterday = now.subtract(const Duration(hours: 24));

Related

Number of days between two Instants doesn't change when changing a specific end date

I have a class that I use to get the number of days between 2 Instants :
public static Long getDaysBetween(final Instant startInstant, final Instant endInstant) {
final ZonedDateTime startDate = startInstant.atZone(ZoneId.systemDefault());
final ZonedDateTime endDate = endInstant.atZone(ZoneId.systemDefault());
return ChronoUnit.DAYS.between(startDate, endDate);
}
And the corresponding test class
class WeekCalculatorTest {
#Test
void givenStartAndEndInstant_whenCalculatingTheNumberOfDaysBetween_thenTheResultShouldBe() {
final String start = "2022-09-01T00:00:00Z";
final String end = "2022-10-31T00:00:00Z";
final Instant startInstant = Instant.parse(start);
final Instant endInstant = Instant.parse(end);
assertThat(WeekCalculator.getDaysBetween(startInstant, endInstant), is(59L));
}
}
I don't understand why when I change the end variable to final String end = "2022-10-30T00:00:00Z";, my test is still passing.

Flutter : DateTime.now().toIso8601String() Math

i have DateTime.now().toIso8601String() = 2022-08-09T03:01:32.223255
how can i find if 3 days have passed since the date ?
You can parse string to DateTime object:
final dateTime = DateTime.now();
final stringDateTime = dateTime.toIso8601String();
final parsedDateTime = DateTime.parse(stringDateTime);
In this case, dateTime and parseDateTime are the same.
Then to find out the time difference use difference DateTime instance method, which returns Duration instance. Example from dart documentation:
final berlinWallFell = DateTime.utc(1989, DateTime.november, 9);
final dDay = DateTime.utc(1944, DateTime.june, 6);
final difference = berlinWallFell.difference(dDay);
print(difference.inDays); // 16592
Use the difference function on DateTime object:
DateTime now = DateTime.now();
DateTime addedThreeDays = DateTime.now().add(Duration(days: 3));
print(3 >= now.difference(addedThreeDays).abs().inDays);

how to set mongo db date format while storing data from date object

I am trying to store POJO in mongo db, having currentDate field. currentDate field is in date type.
date currentDate= new Date();
it stores date in "MMM d, yyyy h:mm:ss a" this format in mongo.
how to change this format? I need to add nanoseconds too.
Are you abel to use DateTime, too? DateTime.Ticks' show you the resolution in 100 nanoseconds.
I had smimilar problems in the past trying to set correct Dates in MongoDB, while saving them directly. I suggest you to create your own DateTime object and save it in the MongoDB?
For example like a SpecifiqueDate
> public class SpecifiqueDate
> {
> public int Year;
> public int Month;
> public int Day;
> public int Houres;
> public int Minutes;
> public int Seconds;
> public long Milliseconds;
> public long Nanoseconds;
>
> public Date(int year, int month, int day, int houres, int minutes, int seconds, long milliseconds, long nanoseconds)
> {
> Year = year;
> Month = month;
> Day = day;
> Houres = houres;
> Minutes = minutes;
> Seconds = seconds;
> Milliseconds = milliseconds;
> Nanoseconds = nanoseconds;
> } }

Time zone effect on Date to LocalDate conversions for dates far in the future

The following test illustrates something I ran across will investigating Date to LocalDate conversions.
For my setup, Java 7 & joda-time 2.7, the conversion of Date to LocalDate and back appears to get a bit off starting around 2038-3-22.
For me, test_2038_3_21 passes, but test_2038_3_22 does not.
Is this a known problem, and if so, is there a work around?
package com.example;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.junit.Test;
public class TimeZoneTest {
#Test
public void test_2038_3_21() {
exerciseDate(2038, 3, 21);
}
#Test
public void test_2038_3_22() {
exerciseDate(2038, 3, 22);
}
static void exerciseDate(int year, int month, int day) {
TimeZone defaultTimeZone = TimeZone.getDefault();
String defaultUserTimezone = System.getProperty("user.timezone");
DateTimeZone defaultDateTimeZone = DateTimeZone.getDefault();
try {
for (String timeZoneId : timeZoneIds()) {
System.setProperty("user.timezone", timeZoneId);
TimeZone.setDefault(TimeZone.getTimeZone(timeZoneId));
DateTimeZone.setDefault(DateTimeZone.forID(timeZoneId));
LocalDate ld = new LocalDate(year, month, day);
DateTime dt = ld.toDateTimeAtStartOfDay();
Date d = ld.toDate();
Date dd = dt.toDate();
LocalDate ld2 = LocalDate.fromDateFields(d);
DateTime dt2 = ld2.toDateTimeAtStartOfDay();
Date d2 = ld2.toDate();
Date dd2 = dt2.toDate();
assertEquals(timeZoneId, ld, ld2);
assertEquals(timeZoneId, dt, dt2);
assertEquals(timeZoneId, d, d2);
assertEquals(timeZoneId, dd, dd2);
assertEquals(timeZoneId, d, dd);
}
} finally {
DateTimeZone.setDefault(defaultDateTimeZone);
System.setProperty("user.timezone", defaultUserTimezone);
TimeZone.setDefault(defaultTimeZone);
}
}
static List<String> timeZoneIds() {
List<String> timeZones = new ArrayList<>();
for (String timeZoneId : TimeZone.getAvailableIDs()) {
try { // only use time zones that DateTimeZone thinks are valid
DateTimeZone.forID(timeZoneId);
timeZones.add(timeZoneId);
} catch (IllegalArgumentException e) {
// ignore
}
}
return timeZones;
}
}
You are likely hitting a DST transition for one of the time zones.
From the docs for LocalDate.toDate:
Converting to a JDK Date is full of complications as the JDK Date constructor doesn't behave as you might expect around DST transitions. This method works by taking a first guess and then adjusting the JDK date until it has the earliest valid instant.
Do note though that future transitions are really just a best guess based on current information. Time zone rules change regularly. For something that far out, there could easily be a change between now and then.

how to return null datetime

I know such questions are repeated but I did not get any result.I must change helical date to Gregorian date and this is my method
public static DateTime ShamsiToMiladi(string shmasi)
{
DateTime? Dt = null;
if (shmasi != "")
{
System.Globalization.PersianCalendar persian = new System.Globalization.PersianCalendar();
char[] spChar = { '/' };
string[] splited_shamsi = shmasi.Split(spChar, 3);
Dt = persian.ToDateTime(int.Parse(splited_shamsi[0]), int.Parse(splited_shamsi[1]), int.Parse(splited_shamsi[2]), 12, 12, 12, 12);
}
return Dt;
}
sahmsi is a parameter that comes from a textbox.what do i return Dt?
thanks for help
Since DateTime is actually a structure built upon a long integer, it cannot be assigned a null value.
But if you need to have that option, declare it as a nullable DateTime thusly:
DateTime? ThisDate = null;
If you do return a nullable DateTime, your caller will have to check for a null value before using as a regular DateTime in expressions.
As a general rule, a newly-declared regular DateTime has a value of DateTime.MinValue ('01/01/0000'), and you can test for that, instead.