how to extract the today's date out of the date column using SQL query? - android-room

I assume I would need to change query in order to sort the data with today's date.
Please tell me how to change it though...
SQL QUERY in ToDoDao
#Query("SELECT * FROM todo_table WHERE date(date) = date('now')")
fun getTodayList(): Flow<List<ToDoTask>>
DATABASE
#Entity(tableName = DATABASE_TABLE)
data class ToDoTask(
#PrimaryKey(autoGenerate = true) val id: Int = 0,
#ColumnInfo(name = "title") val title: String,
#ColumnInfo(name = "description") val description: String,
#ColumnInfo(name = "priority") val priority: Priority,
#ColumnInfo(name = "date") val date: String,
#ColumnInfo(name = "favorite") var favorite: Boolean)
date val in ViewModel class
val date : MutableState<String> = mutableStateOf("")
datas inserted
enter image description here
I have tried the code below and I was able to activate the function as the query as I intented, so I think the query is the issue here.
#Query("SELECT * FROM todo_table WHERE date = '2023-2-14'")
fun getTodayList(): Flow<List<ToDoTask>>

The Issue
The issue is that the SQLite date function expects the date to be in an accepted format.
YYYY-M-DD is not such a format and will result in null rather than a date. YYYY-MM-DD is an accepted format (see https://www.sqlite.org/lang_datefunc.html#time_values). That is leading zeros are used to expand single digit numbers to 2 digit numbers for the month and day of month values.
The Fix (not recommended)
To fix the issue you have shown, you could use (see the However below):-
#Query("SELECT * FROM todo_table WHERE date(substr(date,1,5)||CASE WHEN substr(date,7,1) = '-' THEN '0' ELSE '' END ||substr(date,6)) = date('now');")
If the month was 2 numerics i.e. MM (e.g. 02 for February) then the above would not be necessary.
The CASE WHEN THEN ELSE END construct is similar to IF THEN ELSE END. see https://www.sqlite.org/lang_expr.html#the_case_expression. This is used to add the additional leading 0, when omitted, to the string used by the date function.
However, the above would not cater for days that have the leading 0 omitted for the first 9 days of the month. This due to the 4 permutations of the format (YYYY-MM-DD, YYYY-MM-D, YYYY-M-D and YYYY-M-DD) would be more complex e.g.
#Query("SELECT * FROM todo_table WHERE date(CASE WHEN length(date) = 8 THEN substr(date,1,5)||'0'||substr(date,6,1)||'-0'||substr(date,8) WHEN length(date) = 9 AND substr(date,7,1) = '-' THEN substr(date,1,5)||'0'||substr(date,6) WHEN length(date) = 9 AND substr(date,8,1) = '-' THEN substr(date,1,8)||'0'||substr(date,9) ELSE date END) = date('now');")
Recommended Fix
The recommended fix is to store values using one of the accepted formats rather than try to manipulate values to be an accepted date to then be worked upon using the date and time functions.

Related

Sorting in Java | How to get value from other field of entity if the current field is null while sorting entity list in java?

Context :
Consider following entity in spring boot project,
#Entity
public class Transaction{
#Id
private Integer tId;
private Integer amount;
private LocalDate invoiceDate;
private LocalDate tDate;
}
A method which creates object of transaction, doesn't set tDate.
There is an independent method which sets tDate.
So, in the database some entries don't have 'tDate'.
Problem :
Now, I want to show all the entries in database sorted using tDate but, for those entries which does not contain tDate it should consider invoiceDate.
Sample Database entries
t_id
amount
invoice_date
t_date
1
1200
2/3/2022
4/3/2022
2
2434
5/3/2022
6/3/2022
3
234
3/3/2022
NULL
Sample expected Output
[[tId = 3, amount = 234, invoiceDate = 3/3/2022, tDate = NULL]
[tId = 1, amount = 1200, invoiceDate = 2/3/2022, tDate = 4/3/2022]
[tId = 2, amount = 2434, invoiceDate = 5/3/2022, tDate = 6/3/2022]]
Note : Highlighted dates above are the dates considered for sorting.
What I tried
I tried to use the combination of nullsLast(Comparator.naturalOrder()) and thenComparing() methods of Comparator.comparing() but it doesn't give the expected output. It sorts the entries withtDate and entries without tDate separately.
Thank you in advance for any help!!
Also, I'm using MongoRepository in repository layer, so I can use the Sort object as well.
Thank you!

D3 time string convert to date

I'm new to D3.
I have a string stored in a var, below is the var.
var expense = {"name":"jim","amount":34,"date":"11/12/2015"};
and I want to only show the year of the date.
var parser = d3.timeParse("%Y");
expense.date = parser(expense.date);
console.log(expense);
but I am just getting null for the date. Anyone know how to fix this? I should get the result:
{name: "jim", amount: 34, date: 2015 }
If you want to use d3 date tools, first you have the parse your string to date format
const tParser = d3.timeParse("%d/%m/%Y")
then use on your string
const date = tParser(expense.date)
then use d3.timeFormat("%Y")
const year = d3.timeFormat("%Y")(date)
Or much simpler just split your string as rioV8 commented
expense.date = +expense.date.split('/')[2]
Thought it could be useful to know how to use d3 time format works, more info

java.time.format.DateTimeParseException: Text could not be parsed at index 3

I am using Java 8 to parse the the date and find difference between two dates.
Here is my snippet:
String date1 ="01-JAN-2017";
String date2 = "02-FEB-2017";
DateTimeFormatter df = DateTimeFormatter .ofPattern("DD-MMM-YYYY", en);
LocalDate d1 = LocalDate.parse(date1, df);
LocalDate d2 = LocalDate.parse(date2, df);
Long datediff = ChronoUnit.DAYS.between(d1,d2);
When I run I get the error:
java.time.format.DateTimeParseException: Text could not be parsed at index 3
First of all, check the javadoc. The uppercase D represents the day-of-year field (not the day-of-month as you want), and uppercase Y represents the week-based-year field (not the year as you want). The correct patterns are the lowercase letters d and y.
Also, you're using month names in uppercase letters (JAN and FEB), so your formatter must be case insensitive (the default behaviour is to accept only values like Jan and Feb). And these month names are English abbreviations, so you must also use English locale to make sure it parses the names correctly (using java.util.Locale class).
So, your formatter should be created like this:
DateTimeFormatter df = new DateTimeFormatterBuilder()
// case insensitive to parse JAN and FEB
.parseCaseInsensitive()
// add pattern
.appendPattern("dd-MMM-yyyy")
// create formatter (use English Locale to parse month names)
.toFormatter(Locale.ENGLISH);
This will make your code work (and datediff will be 32).
The following code works. The problem is you are using "JAN" instead of "Jan".
DateTimeFormatter does not recognize that it seems. and also change the pattern to
"d-MMM-yyyy".
String date1 ="01-Jan-2017";
String date2 = "02-Feb-2017";
DateTimeFormatter df = DateTimeFormatter.ofPattern("d-MMM-yyyy");
LocalDate d1 = LocalDate.parse(date1, df);
LocalDate d2 = LocalDate.parse(date2, df);
Long datediff = ChronoUnit.DAYS.between(d1,d2);
Source: https://www.mkyong.com/java8/java-8-how-to-convert-string-to-localdate/
// DateTimeFormatterBuilder provides custom way to create a
// formatter
// It is Case Insensitive, Nov , nov and NOV will be treated same
DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
LocalDate datetime = LocalDate.parse("2019-DeC-22", f);
System.out.println(datetime); // 2019-12-22
} catch (DateTimeParseException e) {
// Exception handling message/mechanism/logging as per company standard
}
Maybe Someone is looking for this it will work with date Format like 3/24/2022 or 11/24/2022
DateTimeFormatter.ofPattern("M/dd/yyyy")
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yyyy");
formatter = formatter.withLocale( Locale.US ); // Locale specifies human language for translating, and cultural norms for lowercase/uppercase and abbreviations and such. Example: Locale.US or Locale.CANADA_FRENCH
LocalDate date = LocalDate.parse("3/24/2022", formatter);
System.out.println(date);
Maybe you can use this wildcard,
String d2arr[] = {
"2016-12-21",
"1/17/2016",
"1/3/2016",
"11/23/2016",
"OCT 20 2016",
"Oct 22 2016",
"Oct 23", // default year is 2016
"OCT 24", // default year is 2016
};
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
.parseCaseInsensitive().parseLenient()
.parseDefaulting(ChronoField.YEAR_OF_ERA, 2016L)
.appendPattern("[yyyy-MM-dd]")
.appendPattern("[M/dd/yyyy]")
.appendPattern("[M/d/yyyy]")
.appendPattern("[MM/dd/yyyy]")
.appendPattern("[MMM dd yyyy]");
DateTimeFormatter formatter2 = builder.toFormatter(Locale.ENGLISH);
https://coderanch.com/t/677142/java/DateTimeParseException-Text-parsed-unparsed-textenter link description here
Try using DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-LLL-yyyy",Locale.ENGLISH);

Python Datetime string parsing: How to know what has been parsed?

I want to use Python to parse a user input string and need to know which portion of date has been specified, e.g.,
"Jan. 2017" => Month = 1, Year = 2017
The result should tell me only month and year are specified in the string, and return those values, while:
"2003-05-01"
specifies day, month and year.
I tried to use dateutil.parser.parse, and gave it a rare default date value. e.g., 1900/01/01, and then compare the parsed result with the default date and see the difference. But if the month or day are both 1 in the parsed result,
it needs one more round of parsing with a different default value, in order to rule out the possibility of it being the default value, or from the user input.
The above way seems quirky. Is there a library for me to parse commonly used date string format and knowing what has been parsed?
I ended up doing the quirky way:
from dateutil.parser import parse
# parse the date str, and return day/month/year specified in the string.
# the value is None if the string does not have information
def parse_date(date_str):
# choose two different dates and see if two parsed results
default_date1 = datetime.datetime(1900, 1, 1, 0, 0)
default_date2 = datetime.datetime(1901, 12, 12, 0, 0)
year = None
month = None
day = None
try:
parsed_result1 = parse(date_str, default=default_date1)
parsed_result2 = parse(date_str, default=default_date2)
if parsed_result1.year == parsed_result2.year: year = parsed_result2.year
if parsed_result1.month == parsed_result2.month: month = parsed_result2.month
if parsed_result1.day == parsed_result2.day: day = parsed_result2.day
return year, month, day
except ValueError:
return None, None, None

It is possible to avoid making condition in 12:00 time?

Hello I have this code below to format 12 hrs from my mvc3 controller to my jqgrid. I have a value of null from my database but it return 12:00 I want is if it is null I want to return a blank space or blank.
string FitaIn1 = Convert.ToDateTime(req.FAIn1).ToString("hh:mm");
string FitaOut1 = Convert.ToDateTime(req.FAOut1).ToString("hh:mm");
string FitaIn2 = Convert.ToDateTime(req.FAIn2).ToString("hh:mm");
string FitaOut2 = Convert.ToDateTime(req.FAOut2).ToString("hh:mm");
string FitaCorIn1 = Convert.ToDateTime(req.FACorrectionIn1).ToString("hh:mm");
string FitaCorOut1 = Convert.ToDateTime(req.FACorrectionOut1).ToString("hh:mm");
string FitaCorIn2 = Convert.ToDateTime(req.FACorrectionIn2).ToString("hh:mm");
string FitaCorOut2 = Convert.ToDateTime(req.FACorrectionOut2).ToString("hh:mm");
At the same time I encounter this problem i try this code below because the null value returns 12:00
if (FitaIn1 == "12:00") { FitaIn1 = "00:00"; }
It is possible to log-in / log-out in 12:00 noon right?. I'm out of idea.

Resources