ruby, date string between date string range - ruby

I have two date strings :
lower_limit = '1981-03-27'
upper_limit = '1981-04-27'
and a date string:
birth_date = '1981-03-29'
How to test if birth_date is between lower_limit and upper_limit
Thanks,

This way
(Date.parse(lower_limit)..Date.parse(upper_limit)).cover?(Date.parse(birth_date))

Related

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

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.

How to get TimeZone offset value in java

I have a date coming from a device and I want to do the following in Java:
I want to parse this date "2021-05-27T18:47:07+0530" to yyyy-mm-dd HH:MM:SS
Get the Date's offset value so that I can get the timezone offset as +05:30 or whatever timezone it comes from.
For the first one I have done this and looks like it works, but any better smaller approach will be handy as well:
String date = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ss+SSSS";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
LocalDateTime inputDate = null;
String outputDate = null;
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);
inputDate = LocalDateTime.parse(date, inputFormatter);
outputDate = outputFormatter.format(inputDate);
System.out.println("inputDate: " + inputDate);
System.out.println("outputDate: " + outputDate);
The Ouput is:
inputDate: 2021-05-27T18:47:07.053
outputDate: 2021-05-27 18:47:07
I don't know how to get the offset value of timezone in this case.
There are many recommendations including using SimpleDateFormat and ZonedDateTime etc but should be the best answer for this considering the offset value can be dynamic i.e it can be +05:30,+09:00 etc.
Please help in this case.
Try it like this.
String dateTime = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ssZ";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ",
Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(dateTime, dtf);
ZoneOffset tz = zdt.getOffset();
System.out.println(tz);
System.out.println(zdt.format(DateTimeFormatter.ofPattern(outputPattern,
Locale.ENGLISH)));
Prints
+05:30
2021-05-27 18:47:07
The zoned date time could also be reprinted using the same format by which it was originally parsed.

Print ZonedDateTime exactly as it is parsed

I have a date string in a format:
String date = 2014-05-05T05:05:00.000
ZonedDateTime zoneDateTime = LocalDateTime.parse(date).atZone(ZoneId.of("UTC");
the above prints:
2014-05-05T05:05Z[UTC]
Is there any way we can print it in the following format ?
2014-05-05T05:05:00.000Z
In joda time, i can easily do this:
DateTime datetime= org.joda.time.LocalDateTime.parse(date).toDateTime(UTC)
Is there any way we can print it in the following format ?
String date = 2014-05-05T05:05:00.000
You can use java.time.format.DateTimeFormatter.ofPattern().
String date = "2014-05-05T05:05:00.000";
ZonedDateTime zoneDateTime = LocalDateTime.parse(date).atZone(ZoneId.of("UTC"));
System.out.println(zoneDateTime);
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX").format(zoneDateTime));
Refrence: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

combine Date and Time into a DateTime from api response

What is the efficient way to combine Date and Time (strings) into a single DateTime? i am using football-api in response i am getting time attribute in "08:50" these format and date attribute "01.01.2018" these format. I want to save in database 2018-01-01 08:50:00 format in date field.
a = match["formatted_date"].to_date.strftime("%Y, %m, %d")
y = a[0..3].to_i
m = a[6..7].to_i
d = a[10..11].to_i
date = Date.new(y, m, d).to_datetime + Time.parse(match["time"]).seconds_since_midnight.seconds

Generate date objects in hour steps between two given dates

Given are two timestamps in the format YYYYMMDDHH, which are perfectly parseable by DateTime.strptime.
What I want to create is a list of strings in the given format from above in one hour steps, starting from the first date up to the second date.
Example input: 2013011515 and 2013011822.
Expected output: ['2013011515','2013011516','2013011517','2013011518', ... , '2013011820', '2013011820', '2013011821', '2013011822']
Is there any ruby library or core functionality to accomplish this task?
You can use step with an hourly resolution if you use ruby 1.9:
date1 = DateTime.strptime('2013011522', '%Y%m%d%H')
date2 = DateTime.strptime('2013011622', '%Y%m%d%H')
date_range = date1.step(date2, 1.0/24).to_a
Alternatively, on ruby 1.8.7, use a loop
date1 = DateTime.strptime('2013011522', '%Y%m%d%H')
date2 = DateTime.strptime('2013011622', '%Y%m%d%H')
new_date = date1
date_range = [date1]
date_range << (new_date += 1.0/24) while new_date <= date2
#!/usr/bin/env ruby
dt_from = "2013011515"
dt_to = "2013011822"
require 'date'
date_from = Date.parse(dt_from[0,8])
date_to = Date.parse(dt_to[0,8])
res = []
date = date_from
while (date <= date_to)
if date == date_from
hours = (dt_from[8,2].to_i..23).to_a
elsif date == date_to
hours = (0..dt_to[8,2].to_i).to_a
else
hours = (0..23).to_a
end
hours.each {|h| res << "#{date.strftime('%Y%m%d')}#{"%02d" % h}"}
date += 1
end
puts res.inspect

Resources