SQFlite rawquery to get the closest datetime - flutter

I'm programming a birthday app and want to use sqflite to sort the nearest date.
Through the page: SQLite query to get the closest datetime
I found out about strftime, but unfortunately I don't know how to use it with Flutter. Here are some examples how to sort a date and how I try to find the current date with strftime.
Future<List<Map<String, dynamic>>> getSortDateMapListToDate(bool sort) async {
Database db = await this.database;
String sortingDirection = '$colDate DESC';
if(!sort) {
sortingDirection = '$colDate ASC';
}
DateTime test = DateTime.now();
//var result = await db.query(dateTable, orderBy: sortingDirection);
var result = await db.rawQuery('SELECT * from $dateTable orderBy abs(strftime("%s",$test) - strftime("%s", $colDate))');
return result;
}
Maybe there is another possibility or someone has already worked with rawquerys and strftime.
For any kind of tip or help I would be grateful.
EDIT:
With the help from #heitor murara i edit my code:
var result = await db.rawQuery(
"SELECT s.id, s.name, s.date, s.priority, (strftime('%y-%m-%d', '2020-06-30') - strftime('%y-%m-%d', s.$colDate)) as 'TestDate' "
"FROM $dateTable s "
"ORDER BY TestDate"
);
the dates i use: 30.06.2020 and with strftime('%s) i get the rows:
2015-08-15 // 32 remaining days
2010-11-03 // 126 remaining days
2010-07-10 // 10 remaining days
1994-07-17 // 17 remaining days
1993-06-29 // 364 remaining days
with strftime('%y-%m-%d) i get the rows:
1994-07-17 // 17 remaining days
1993-06-29 // 364 remaining days
2015-08-15 // 32 remaining days
2010-11-03 // 126 remaining days
2010-07-10 // 10 remaining days
what I am trying to achieve:
2010-07-10 // 10 remaining days
1994-07-17 // 17 remaining days
2015-08-15 // 32 remaining days
2010-11-03 // 126 remaining days
1993-06-29 // 364 remaining days
a other solution that is in my mind, would be a trigger, who "check" every day if the date changes, the remaining days are calculated dynamically.
Has someone a hint? :)

The strftime() function you are using do this:
The strftime() routine returns the date formatted according to the format string specified as the first argument.
So, if all your dates were in a format like this: 2020-06-28 you could run a rawQuery simply like this to make the ordering:
SELECT d FROM datetime_text ORDER BY d ASC;
However, if they are not, you can then use the strftime() function to format your date to than order:
SELECT strftime('%Y-%m-%d', d) FROM datetime_text ORDER BY d ASC;
The dates would be returned in something like this:
2020-06-27
2020-06-28
2020-06-28
2020-06-28
2020-06-29
In your example, I believe you can achieve what you want with something like this:
var result = await db.rawQuery("SELECT strftime('%Y-%m-%d', <column-name>) FROM $dateTable ORDERBY $sortingDirection");
As you can see I replaced the * from your query by a <column-name> just update it with your column name.
Ps.: Since you are working with birthdays, the format '%Y-%m-%d' will do the job, you don't need to use times also.

Related

flutter datetime how to convert it

I have the following datetime from a database: 2022-10-02T23:10:24.736Z I want to compare it to a datetime now and get the difference in second. Basically I have the code for it, but im not able to convert the datetime.now to the mentioned format. It tells me it has a difference of 122 minutes but it should only be 2 minutes..
DateTime datenow = DateTime.now();
DateTime dateFormDatabase = DateTime.parse(widget.data[widget.currIndex-1]["roundEnd"]);
print(datenow); // <---- 2022-10-01 23:22:45.522687
print(dateFormDatabase); // <--- 2022-10-01 23:25:24.736Z
var diff = dateFormDatabase.difference(datenow);
print(diff.inMinutes); // <--- 122 but it should be 2minutes
The returned difference is correct. You are probably looking at different timezones here. DateTime.now() returns the current date and time in your local timezone. The parsed date from your database seems to be coming in as UTC. Notice the "Z" at the end here: 2022-10-01 23:25:24.736Z.
If you want to visually compare them you could convert either of those to UTC/local with toUtc or toLocal

how to find difference btw 21:00 pm - 1:00 am in flutter

can someone please humbly help me? im fining it extremely confusing.
the dates are like this
1st date ~ 2 May 21:00
2nd date ~ 3 May 04:00
Let's say we have two dates.
var d1 = '2 May 04:00';
var d2 = '3 May 05:00';
First, add this intl package to your project and import it
import 'package:intl/intl.dart';
Next, you need to set a dateformat for your dates above:
var dFormat = DateFormat('d MMM HH:mm');
The date format should be same as your dates orelse you will get an error.
Next, convert the datetime string to your desired format.
var dateTime1 = dFormat.parse(d1, true);
var dateTime2 = dFormat.parse(d2, true);
You can set true if you want UTC time.
Lastly, to get difference between two dates just do the following:
print(dateTime2.difference(dateTime1).inHours); //25
The above print statement will return 25 as the difference between both the given time is 25hours. You can get difference in Minutes too.
Happy Coding!

Number of days in a month in DB2

Is there a way to find the number of days in a month in DB2. For example I have a datetime field which I display as Jan-2020, Feb-2020 and so on. Based on this field I need to fetch the number of days for that month. The output should be something like below table,
I'm using the below query
select reportdate, TO_CHAR(reportdate, 'Mon-YYYY') as textmonth from mytable
Expected output
ReportDate textMonth No of Days
1-1-2020 08:00 Jan-2020 31
1-2-2020 09:00 Feb-2020 29
12-03-2020 07:00 Mar-2020 31
Try this:
/*
WITH MYTABLE (reportdate) AS
(
VALUES
TIMESTAMP('2020-01-01 08:00:00')
, TIMESTAMP('2020-02-01 09:00:00')
, TIMESTAMP('2020-03-12 07:00:00')
)
*/
SELECT reportdate, textMonth, DAYS(D + 1 MONTH) - DAYS(D) AS NO_OF_DAYS
FROM
(
SELECT
reportdate, TO_CHAR(reportdate, 'Mon-YYYY') textMonth
, DATE(TO_DATE('01-' || TO_CHAR(reportdate, 'Mon-YYYY'), 'dd-Mon-yyyy')) D
FROM MYTABLE
);
Db2 has the function DAYS_TO_END_OF_MONTH and several others which you could use. Based on your month input, construct the first day of the month. This should be something like 2020-01-01 for Jan-2020 or 2020-02-01 for Feb-2020. Follow the link for several other conversion functions which allow you to transform between formats and to perform date arithmetics.
convert your column to a proper date and try this: day(last_day(date_column))

convert year-month string into daily dates

recently I asked how to convert calendar weeks into a list of dates and received a great and most helpful answer:
convert calendar weeks into daily dates
I tried to apply the above method to create a list of dates based on a column with "year - month". Alas i cannot make out how to account for the different number of days in different months.
And I wonder whether the package lubridate 'automatically' takes leap years into account?
Sample data:
df <- data.frame(YearMonth = c("2016 - M02", "2016 - M06"), values = c(28,60))
M02 = February, M06 = June (M11 would mean November, etc.)
Desired result:
DateList Values
2016-02-01 1
2016-02-02 1
ect
2016-02-28 1
2016-06-01 2
etc
2016-06-30 2
Values would something like
df$values / days_in_month()
Thanks a million in advance - it is honestly very much appreciated!
I'll leave the parsing of the line to you.
To find the last day of a month, assuming you have GNU date, you can do this:
year=2016
month=02
last_day=$(date -d "$year-$month-01 + 1 month - 1 day" +%d)
echo $last_day # => 29 -- oho, a leap year!
Then you can use a for loop to print out each day.
thanks to answer 6 at Add a month to a Date and answer for (how to extract number with leading 0) i got an idea to solve my own question using lubridate. It might not be the most elegant way, but it works.
sample data
data <- data_frame(mon=c("M11","M02"), year=c("2013","2014"), costs=c(200,300))
step 1: create column with number of month
temp2 <- gregexpr("[0-9]+", data$mon)
data$monN <- as.numeric(unlist(regmatches(data$mon, temp2)))
step 2: from year and number of month create a column with the start date
data$StartDate <- as.Date(paste(as.numeric(data$year), formatC(data$monN, width=2, flag="0") ,"01", sep = "-"))
step 3: create a column EndDate as last day of the month based on startdate
data$EndDate <- data$StartDate
day(data$EndDate) <- days_in_month(data$EndDate)
step 4: apply answer from Apply seq.Date using two dataframe columns to create daily list for respective month
data$id <- c(1:nrow(data))
dataL <- setDT(data)[,list(datelist=seq(StartDate, EndDate, by='1 day'), costs= costs/days_in_month(EndDate)) , by = id]

Date query with the current date between two date_time columns

I have a fusion table with two date_time columns. The fist one is the start date (Startdatum) and in the other column is the end date (Einddatum).
I want to do a query with the current date, and only show the KML-lines on a map where the current date lies between the start and end date.
I tried to use the code below to create a string with a date format:
var time_date = new Date();
var day = time_date.getDate();
var month = time_date.getMonth()+1;
var year = time_date.getFullYear();
var date = (year+"."+month+"."+day);
To show the KML-lines on the map I tried to use the following code:
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col2",
from: "1mOMP1seJq4FdiNTugsfylZaJc8sKcSlfJKUuTJjv",
where: "'Startdatum' <= date AND 'Einddatum' >= date"
},
options: {
styleId: 2,
templateId: 2
}
});
Unfortunatly the map shows all the KMS-lines regardless what date is in one of the columns.
What am I doing wrong?
the where-clause is wrong, it has to be
where: "Startdatum <= '"+date+"' AND Einddatum >= '"+date+"'"
the date-format seems to be wrong. Although the used format yyyy.MM.dd is defined in the documentation, it doesn't work. The format yyyy-MM-dd currently works for me(but it's not defined in the documentation).
var date = (year+"-"+month+"-"+day);
(in case that day and month be less than 10 they wouldn't match the pattern, but that doesn't seem to be an issue)
Beyond that: when you fix these 2 mentioned parts it currently works(for me), but I've tried it a couple of hours ago and got unstable results.